• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

541
Views
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?
over 3 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 3 years ago · Santiago Trujillo Report

0

you probably need manually add/remove listener

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

// unsubscribe
this.handler();
over 3 years ago · Santiago Trujillo Report

0

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 {};
over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error