13

How can I removed @Hostlistener() in Angular 2, like used removeEventListener in Native JS?

Example: I have many dropDown components in my page. When dropDown opened I want to add handler on document click event and to remove handler when dropDown closed.

Native JS:

function handler(){
  //do something
}
document.addEventListener('click', handler); // add handler
document.removeEventListener('click', handler); // remove handler

Angular 2:

  @HostListener('document: click') onDocumentClick () {
    // do something
  }

  // How can I remove handler?
Smiranin
  • 738
  • 1
  • 5
  • 14

3 Answers3

8

Julia Passynkova Answer is almost correct.

Just remove the quotation marks around "document", like this:

// subscribe
this.handler = this.renderer.listen(document, "click", event =>{...});

// unsubscribe
this.handler();

Annotation:

I find @Smiranin comment quite usefull. As Angular 2 makes use of Rxjs, a better way would be to create a dedicated service for these types of events and expose subjects on it. Components can than consume the subjects event stream resulting in the same behaviour. This would make the code more decoupled, easier to test and robust to API changes.

Armin Bu
  • 1,330
  • 9
  • 17
  • 1
    Thank you, this is a good solution, but it has two problems. 1) We use a global variable (document), I think that a bad idea will be to use the global variable in the component. For testing. 2) We always have to remove the handler on the Destroy hook. If we use @RemoveHostingListener, the method would do this instead of us – Smiranin Jun 08 '17 at 19:26
  • 1
    I found another solution. Use the service in which to create the observable from event. I always have only one handler on document, but any component can use it. – Smiranin Jun 08 '17 at 19:32
  • there is no such function in angular 2+ @RemoveHostingListener .... see this topic: https://github.com/angular/angular/issues/16366 – yehonatan yehezkel Feb 13 '19 at 21:31
5

you probably need manually add/remove listener

// subscribe
this.handler = this.renderer.listen('document', "click", event =>{...});

// unsubscribe
this.handler();
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
2

The best I've managed is to essentially add/remove the method attached to the listener.

First setup the listener:

@HostListener('document:click', ['$event'])
handler(event: any) : void {};

Then insert this code as fits for your solution:

//add handler
this.handler = function(event: any) : void {
    // do something
}

//remove handler
this.handler = function() : void {};
  • Does this actually result in the event handler being destroyed? Seems like the event listener (outside of Angular) would persist, which results in a memory leak. – elliottregan Oct 15 '21 at 21:34