Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

637
Views
Angular 2. Eliminar @Hostlistener()

¿Cómo puedo eliminar @Hostlistener() en Angular 2, como removeEventListener usado en Native JS?

Ejemplo: tengo muchos componentes desplegables en mi página. Cuando se abre el menú desplegable, quiero agregar un controlador en el evento de clic del documento y eliminar el controlador cuando se cierra el menú desplegable.

JS nativo:

 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 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Julia Passynkova La respuesta es casi correcta.

Simplemente elimine las comillas alrededor de "documento", así:

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

Anotación:

Encuentro el comentario de @Smiranin bastante útil. Como Angular 2 hace uso de Rxjs, una mejor manera sería crear un servicio dedicado para este tipo de eventos y exponer temas en él. Los componentes pueden consumir el flujo de eventos de los sujetos, lo que da como resultado el mismo comportamiento. Esto haría que el código fuera más desacoplado, más fácil de probar y resistente a los cambios de la API.

over 4 years ago · Santiago Trujillo Report

0

probablemente necesite agregar/eliminar manualmente el oyente

 // subscribe this.handler = this.renderer.listen('document', "click", event =>{...}); // unsubscribe this.handler();
over 4 years ago · Santiago Trujillo Report

0

Lo mejor que he logrado es esencialmente agregar/eliminar el método adjunto al oyente.

Primero configure el oyente:

 @HostListener('document:click', ['$event']) handler(event: any) : void {};

Luego inserte este código según se ajuste a su solución:

 //add handler this.handler = function(event: any) : void { // do something } //remove handler this.handler = function() : void {};
over 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!