Javascript removeEventListener OnDestroy not working in Angular 6





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am trying to removeEventListener in my angular compenent: Javascript removeEventListener not working



    ...
ngOnInit() {
document.addEventListener('visibilitychange', () =>this.handleVisibleState(), true);
}

ngOnDestroy() {
document.removeEventListener('visibilitychange', () => this.handleVisibleState(), true);
}

handleVisibleState() {
let vis = document.visibilityState === 'visible';
this.configsService.update_collab_visible(vis);
}
...


with the above addEventListener works even after ngOnDestroy ()



How can I unbind visibilityState from document in angular components?



attempt 2



    private visibilityChangeCallback: () => void;

ngOnInit() {
this.visibilityChangeCallback = () => this.handleVisibleState();
document.addEventListener('visibilitychange', this.handleVisibleState, true);
}

ngOnDestroy() {
document.removeEventListener('visibilitychange', this.handleVisibleState, true);
}

handleVisibleState() {
let vis = document.visibilityState === 'visible';
console.log(typeof this.configsService); // undefined
this.configsService.update_collab_visible(vis);
}


result:




ERROR TypeError: Cannot read property 'update_collab_visible' of undefined











share|improve this question































    0















    I am trying to removeEventListener in my angular compenent: Javascript removeEventListener not working



        ...
    ngOnInit() {
    document.addEventListener('visibilitychange', () =>this.handleVisibleState(), true);
    }

    ngOnDestroy() {
    document.removeEventListener('visibilitychange', () => this.handleVisibleState(), true);
    }

    handleVisibleState() {
    let vis = document.visibilityState === 'visible';
    this.configsService.update_collab_visible(vis);
    }
    ...


    with the above addEventListener works even after ngOnDestroy ()



    How can I unbind visibilityState from document in angular components?



    attempt 2



        private visibilityChangeCallback: () => void;

    ngOnInit() {
    this.visibilityChangeCallback = () => this.handleVisibleState();
    document.addEventListener('visibilitychange', this.handleVisibleState, true);
    }

    ngOnDestroy() {
    document.removeEventListener('visibilitychange', this.handleVisibleState, true);
    }

    handleVisibleState() {
    let vis = document.visibilityState === 'visible';
    console.log(typeof this.configsService); // undefined
    this.configsService.update_collab_visible(vis);
    }


    result:




    ERROR TypeError: Cannot read property 'update_collab_visible' of undefined











    share|improve this question



























      0












      0








      0








      I am trying to removeEventListener in my angular compenent: Javascript removeEventListener not working



          ...
      ngOnInit() {
      document.addEventListener('visibilitychange', () =>this.handleVisibleState(), true);
      }

      ngOnDestroy() {
      document.removeEventListener('visibilitychange', () => this.handleVisibleState(), true);
      }

      handleVisibleState() {
      let vis = document.visibilityState === 'visible';
      this.configsService.update_collab_visible(vis);
      }
      ...


      with the above addEventListener works even after ngOnDestroy ()



      How can I unbind visibilityState from document in angular components?



      attempt 2



          private visibilityChangeCallback: () => void;

      ngOnInit() {
      this.visibilityChangeCallback = () => this.handleVisibleState();
      document.addEventListener('visibilitychange', this.handleVisibleState, true);
      }

      ngOnDestroy() {
      document.removeEventListener('visibilitychange', this.handleVisibleState, true);
      }

      handleVisibleState() {
      let vis = document.visibilityState === 'visible';
      console.log(typeof this.configsService); // undefined
      this.configsService.update_collab_visible(vis);
      }


      result:




      ERROR TypeError: Cannot read property 'update_collab_visible' of undefined











      share|improve this question
















      I am trying to removeEventListener in my angular compenent: Javascript removeEventListener not working



          ...
      ngOnInit() {
      document.addEventListener('visibilitychange', () =>this.handleVisibleState(), true);
      }

      ngOnDestroy() {
      document.removeEventListener('visibilitychange', () => this.handleVisibleState(), true);
      }

      handleVisibleState() {
      let vis = document.visibilityState === 'visible';
      this.configsService.update_collab_visible(vis);
      }
      ...


      with the above addEventListener works even after ngOnDestroy ()



      How can I unbind visibilityState from document in angular components?



      attempt 2



          private visibilityChangeCallback: () => void;

      ngOnInit() {
      this.visibilityChangeCallback = () => this.handleVisibleState();
      document.addEventListener('visibilitychange', this.handleVisibleState, true);
      }

      ngOnDestroy() {
      document.removeEventListener('visibilitychange', this.handleVisibleState, true);
      }

      handleVisibleState() {
      let vis = document.visibilityState === 'visible';
      console.log(typeof this.configsService); // undefined
      this.configsService.update_collab_visible(vis);
      }


      result:




      ERROR TypeError: Cannot read property 'update_collab_visible' of undefined








      angular typescript angular-routing






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 19:00







      Omar

















      asked Nov 16 '18 at 18:49









      OmarOmar

      9031226




      9031226
























          4 Answers
          4






          active

          oldest

          votes


















          1














          Store the callback:



          private visibilityChangeCallback: () => void;

          ngOnInit() {
          this.visibilityChangeCallback = () => this.handleVisibleState();
          document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
          }

          ngOnDestroy() {
          document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
          }





          share|improve this answer


























          • I guess self.handleVisibleState() should be this.handleVisibleState()

            – Sunil Singh
            Nov 16 '18 at 18:54











          • see my question. I added why that didnt work

            – Omar
            Nov 16 '18 at 19:00











          • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.

            – Frank Modica
            Nov 16 '18 at 19:02











          • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.

            – Frank Modica
            Nov 16 '18 at 19:10



















          2














          You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



          The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



          ngOnInit() {
          document.addEventListener('visibilitychange', this.handleVisibleState, true);
          }

          ngOnDestroy() {
          document.removeEventListener('visibilitychange', this.handleVisibleState, true);
          }

          handleVisibleState = () => {
          let vis = document.visibilityState === 'visible';
          this.configsService.update_collab_visible(vis);
          };


          There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



          destroy = new Subject<void>();

          ngOnInit() {
          fromEvent(document, 'visibilitychange', true).pipe(
          takeUntil(this.destroy)
          ).subscribe((event) => this.handleVisibleState(event));
          }

          ngOnDestroy() {
          this.destroy.next();
          this.destroy.complete();
          }


          advertisement



          There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



          @HostListener('document:visibilitystate.c')
          handleVisibleState() {
          let vis = document.visibilityState === 'visible';
          this.configsService.update_collab_visible(vis);
          }


          and you're done






          share|improve this answer


























          • the last one will destroy automatically?

            – Omar
            Nov 16 '18 at 19:04











          • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually

            – PierreDuc
            Nov 16 '18 at 19:05













          • I dont understand how the 3rd option's listener is registered?

            – Omar
            Nov 16 '18 at 19:13











          • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does

            – PierreDuc
            Nov 16 '18 at 19:18





















          1














          Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. You're passing other function to that.



          Using instance arrow function should help in your case:



          ngOnInit() {
          document.addEventListener('visibilitychange', this.handleVisibleState, true);
          }

          ngOnDestroy() {
          document.removeEventListener('visibilitychange', this.handleVisibleState, true);
          }

          handleVisibleState = () => {
          let vis = document.visibilityState === 'visible';
          this.configsService.update_collab_visible(vis);
          }





          share|improve this answer































            0














            This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



            If you bind this it should work.



            document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






            share|improve this answer



















            • 1





              The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.

              – Frank Modica
              Nov 16 '18 at 19:08












            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343747%2fjavascript-removeeventlistener-ondestroy-not-working-in-angular-6%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Store the callback:



            private visibilityChangeCallback: () => void;

            ngOnInit() {
            this.visibilityChangeCallback = () => this.handleVisibleState();
            document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }





            share|improve this answer


























            • I guess self.handleVisibleState() should be this.handleVisibleState()

              – Sunil Singh
              Nov 16 '18 at 18:54











            • see my question. I added why that didnt work

              – Omar
              Nov 16 '18 at 19:00











            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.

              – Frank Modica
              Nov 16 '18 at 19:02











            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.

              – Frank Modica
              Nov 16 '18 at 19:10
















            1














            Store the callback:



            private visibilityChangeCallback: () => void;

            ngOnInit() {
            this.visibilityChangeCallback = () => this.handleVisibleState();
            document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }





            share|improve this answer


























            • I guess self.handleVisibleState() should be this.handleVisibleState()

              – Sunil Singh
              Nov 16 '18 at 18:54











            • see my question. I added why that didnt work

              – Omar
              Nov 16 '18 at 19:00











            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.

              – Frank Modica
              Nov 16 '18 at 19:02











            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.

              – Frank Modica
              Nov 16 '18 at 19:10














            1












            1








            1







            Store the callback:



            private visibilityChangeCallback: () => void;

            ngOnInit() {
            this.visibilityChangeCallback = () => this.handleVisibleState();
            document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }





            share|improve this answer















            Store the callback:



            private visibilityChangeCallback: () => void;

            ngOnInit() {
            this.visibilityChangeCallback = () => this.handleVisibleState();
            document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 16 '18 at 18:55

























            answered Nov 16 '18 at 18:51









            Frank ModicaFrank Modica

            6,6642829




            6,6642829













            • I guess self.handleVisibleState() should be this.handleVisibleState()

              – Sunil Singh
              Nov 16 '18 at 18:54











            • see my question. I added why that didnt work

              – Omar
              Nov 16 '18 at 19:00











            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.

              – Frank Modica
              Nov 16 '18 at 19:02











            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.

              – Frank Modica
              Nov 16 '18 at 19:10



















            • I guess self.handleVisibleState() should be this.handleVisibleState()

              – Sunil Singh
              Nov 16 '18 at 18:54











            • see my question. I added why that didnt work

              – Omar
              Nov 16 '18 at 19:00











            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.

              – Frank Modica
              Nov 16 '18 at 19:02











            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.

              – Frank Modica
              Nov 16 '18 at 19:10

















            I guess self.handleVisibleState() should be this.handleVisibleState()

            – Sunil Singh
            Nov 16 '18 at 18:54





            I guess self.handleVisibleState() should be this.handleVisibleState()

            – Sunil Singh
            Nov 16 '18 at 18:54













            see my question. I added why that didnt work

            – Omar
            Nov 16 '18 at 19:00





            see my question. I added why that didnt work

            – Omar
            Nov 16 '18 at 19:00













            In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.

            – Frank Modica
            Nov 16 '18 at 19:02





            In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.

            – Frank Modica
            Nov 16 '18 at 19:02













            @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.

            – Frank Modica
            Nov 16 '18 at 19:10





            @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.

            – Frank Modica
            Nov 16 '18 at 19:10













            2














            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



            ngOnInit() {
            document.addEventListener('visibilitychange', this.handleVisibleState, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.handleVisibleState, true);
            }

            handleVisibleState = () => {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            };


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done






            share|improve this answer


























            • the last one will destroy automatically?

              – Omar
              Nov 16 '18 at 19:04











            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually

              – PierreDuc
              Nov 16 '18 at 19:05













            • I dont understand how the 3rd option's listener is registered?

              – Omar
              Nov 16 '18 at 19:13











            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does

              – PierreDuc
              Nov 16 '18 at 19:18


















            2














            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



            ngOnInit() {
            document.addEventListener('visibilitychange', this.handleVisibleState, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.handleVisibleState, true);
            }

            handleVisibleState = () => {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            };


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done






            share|improve this answer


























            • the last one will destroy automatically?

              – Omar
              Nov 16 '18 at 19:04











            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually

              – PierreDuc
              Nov 16 '18 at 19:05













            • I dont understand how the 3rd option's listener is registered?

              – Omar
              Nov 16 '18 at 19:13











            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does

              – PierreDuc
              Nov 16 '18 at 19:18
















            2












            2








            2







            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



            ngOnInit() {
            document.addEventListener('visibilitychange', this.handleVisibleState, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.handleVisibleState, true);
            }

            handleVisibleState = () => {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            };


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done






            share|improve this answer















            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



            ngOnInit() {
            document.addEventListener('visibilitychange', this.handleVisibleState, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.handleVisibleState, true);
            }

            handleVisibleState = () => {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            };


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 16 '18 at 19:07

























            answered Nov 16 '18 at 18:55









            PierreDucPierreDuc

            31.6k56280




            31.6k56280













            • the last one will destroy automatically?

              – Omar
              Nov 16 '18 at 19:04











            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually

              – PierreDuc
              Nov 16 '18 at 19:05













            • I dont understand how the 3rd option's listener is registered?

              – Omar
              Nov 16 '18 at 19:13











            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does

              – PierreDuc
              Nov 16 '18 at 19:18





















            • the last one will destroy automatically?

              – Omar
              Nov 16 '18 at 19:04











            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually

              – PierreDuc
              Nov 16 '18 at 19:05













            • I dont understand how the 3rd option's listener is registered?

              – Omar
              Nov 16 '18 at 19:13











            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does

              – PierreDuc
              Nov 16 '18 at 19:18



















            the last one will destroy automatically?

            – Omar
            Nov 16 '18 at 19:04





            the last one will destroy automatically?

            – Omar
            Nov 16 '18 at 19:04













            @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually

            – PierreDuc
            Nov 16 '18 at 19:05







            @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually

            – PierreDuc
            Nov 16 '18 at 19:05















            I dont understand how the 3rd option's listener is registered?

            – Omar
            Nov 16 '18 at 19:13





            I dont understand how the 3rd option's listener is registered?

            – Omar
            Nov 16 '18 at 19:13













            @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does

            – PierreDuc
            Nov 16 '18 at 19:18







            @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does

            – PierreDuc
            Nov 16 '18 at 19:18













            1














            Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. You're passing other function to that.



            Using instance arrow function should help in your case:



            ngOnInit() {
            document.addEventListener('visibilitychange', this.handleVisibleState, true);
            }

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.handleVisibleState, true);
            }

            handleVisibleState = () => {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }





            share|improve this answer




























              1














              Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. You're passing other function to that.



              Using instance arrow function should help in your case:



              ngOnInit() {
              document.addEventListener('visibilitychange', this.handleVisibleState, true);
              }

              ngOnDestroy() {
              document.removeEventListener('visibilitychange', this.handleVisibleState, true);
              }

              handleVisibleState = () => {
              let vis = document.visibilityState === 'visible';
              this.configsService.update_collab_visible(vis);
              }





              share|improve this answer


























                1












                1








                1







                Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. You're passing other function to that.



                Using instance arrow function should help in your case:



                ngOnInit() {
                document.addEventListener('visibilitychange', this.handleVisibleState, true);
                }

                ngOnDestroy() {
                document.removeEventListener('visibilitychange', this.handleVisibleState, true);
                }

                handleVisibleState = () => {
                let vis = document.visibilityState === 'visible';
                this.configsService.update_collab_visible(vis);
                }





                share|improve this answer













                Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. You're passing other function to that.



                Using instance arrow function should help in your case:



                ngOnInit() {
                document.addEventListener('visibilitychange', this.handleVisibleState, true);
                }

                ngOnDestroy() {
                document.removeEventListener('visibilitychange', this.handleVisibleState, true);
                }

                handleVisibleState = () => {
                let vis = document.visibilityState === 'visible';
                this.configsService.update_collab_visible(vis);
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 16 '18 at 19:25









                yurzuiyurzui

                105k12213230




                105k12213230























                    0














                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






                    share|improve this answer



















                    • 1





                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.

                      – Frank Modica
                      Nov 16 '18 at 19:08
















                    0














                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






                    share|improve this answer



















                    • 1





                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.

                      – Frank Modica
                      Nov 16 '18 at 19:08














                    0












                    0








                    0







                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






                    share|improve this answer













                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '18 at 19:07









                    mwilsonmwilson

                    3,31932149




                    3,31932149








                    • 1





                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.

                      – Frank Modica
                      Nov 16 '18 at 19:08














                    • 1





                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.

                      – Frank Modica
                      Nov 16 '18 at 19:08








                    1




                    1





                    The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.

                    – Frank Modica
                    Nov 16 '18 at 19:08





                    The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.

                    – Frank Modica
                    Nov 16 '18 at 19:08


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343747%2fjavascript-removeeventlistener-ondestroy-not-working-in-angular-6%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python