admin管理员组

文章数量:1201145

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?

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?
Share Improve this question asked Apr 26, 2017 at 19:26 SmiraninSmiranin 7461 gold badge5 silver badges14 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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.

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

I would suggest using rxjs:

import { fromEvent, Subscription } from 'rxjs';

Add a global clickSubscription: Subscription in your component; then in ngOnInit you can do:

  ngOnInit(): void {
    this.clickSubscription = fromEvent(document, 'click').subscribe(event => {
       console.log(event);
    })
   }

and in ngOnDestroy:

  ngOnDestroy(): void {
    this.clickSubscription.unsubscribe();
}

本文标签: javascriptAngular 2 Remove Hostlistener()Stack Overflow