Angular 2. Remove @Hostlistener()

11,069

Solution 1

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.

Solution 2

you probably need manually add/remove listener

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

// unsubscribe
this.handler();

Solution 3

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 {};
Share:
11,069

Related videos on Youtube

Smiranin
Author by

Smiranin

Updated on September 14, 2022

Comments

  • Smiranin
    Smiranin over 1 year

    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
    Smiranin almost 7 years
    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
    Smiranin almost 7 years
    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.
  • yehonatan yehezkel
    yehonatan yehezkel about 5 years
    there is no such function in angular 2+ @RemoveHostingListener .... see this topic: github.com/angular/angular/issues/16366
  • elliottregan
    elliottregan over 2 years
    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.