0

I'm listening to a deviceorientationabsolute event like this (on ngOnInit):

 this.deviceOrientationEvent = this.onDeviceOrientation.bind(this);
 window.addEventListener("deviceorientationabsolute", this.deviceOrientationEvent);

I want to stop listening to that event on ngOnDestroy. I tried this:

window.removeEventListener("deviceorientationabsolute", this.deviceOrientationEvent);

But I can still see in the console that it's listening to the event.

What am I doing wrong?

amitairos
  • 2,907
  • 11
  • 50
  • 84

1 Answers1

1

Instead of handling through window.addEventListener method you can handle it using @HostListener as below

@HostListener('window:deviceorientationabsolute', ['$event'])
deviceOrientationAbsoluteEvent(event) { ... }

It will be automatically removed when component will be destroyed

Refer : https://stackoverflow.com/a/41032388/9380944 answer for more details.

Ankit Prajapati
  • 2,670
  • 2
  • 12
  • 22