Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove EventListeners in angular 4

I need to remove the wheel eventlistener immediately after it fired. I tried the following but its not removing the eventlistener.

export class HomeComponent implements OnInit {

    constructor() {}

    ngOnInit() {
       document.querySelector("#section-one").addEventListener("wheel", () => this.myFunction1(), true);
    }

    myFunction1() {
      alert();
      document.querySelector("#section-one").removeEventListener("wheel", this.myFunction1, true);
      console.log("Done!");
    }
}

Any suggestions?

like image 892
Karthik Samyak Avatar asked Oct 24 '17 09:10

Karthik Samyak


People also ask

How do I remove event listeners?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

Do you need to remove event listeners?

TLDR; Always remove event listeners when you don't plan on using them any longer.

Should I remove event listeners before removing elements?

Removing the event listener first always results in lower memory usage (no leaks).


1 Answers

According to the docs:

Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect.

your code shouldn't work.

Possible fix can be as follows:

wheelHandler: any;

ngOnInit() {
    this.wheelHandler = this.myFunction1.bind(this);
    document.querySelector("#section-one").addEventListener("wheel", this.wheelHandler, true);
}

myFunction1() {
    alert();
    document.querySelector("#section-one").removeEventListener("wheel", this.wheelHandler, true);
    console.log("Done!");
}

where wheelHandler is a function referring to the same instance of handler

For more angular way solution see

  • How to listen for mousemove event on Document object in Angular

But AFAIK useCapture parameter is not supported yet. So it's always false

like image 80
yurzui Avatar answered Oct 18 '22 18:10

yurzui