简体   繁体   中英

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?

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.

you probably need manually add/remove listener

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

// unsubscribe
this.handler();

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 {};

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM