Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2. Remove @Hostlistener()

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?
like image 422
Smiranin Avatar asked Apr 26 '17 19:04

Smiranin


People also ask

How do I unsubscribe from HostListener?

You can't unsubscribe from host-listener. If you need to unsubscribe you need to subscribe imperatively.

Can we use HostListener in component?

Introduction. @HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.


1 Answers

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.

like image 174
Armin Bu Avatar answered Sep 18 '22 11:09

Armin Bu