0

I'm trying to remove all my event listeners when route changes with ngOnDestroy, but I couldn't find a way to do it.

The callbacks in each listener is a method from my component with 'this' binded.

My code looks like this at the moment:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-partners-promote-geolocation',
  templateUrl: './partners-promote-geolocation.component.html'
})
export class PartnersPromoteGeolocationComponent implements OnInit {

constructor () {}

  ngOnInit() {
    document.addEventListener('scroll', this.infoWindowPositionState.bind(this))
    document.addEventListener('click', this.infoWindowVisibilityState.bind(this))
  }

  ngOnDestroy () {
    document.removeEventListener('scroll', this.infoWindowPositionState.bind(this))
    document.removeEventListener('click', this.infoWindowVisibilityState.bind(this))
  }

  infoWindowPositionState () {
    (...)
  }

  infoWindowVisibilityState () {
    (...)
  }

}

I can add the event listeners normally, but when the route changes those events aren't removed. In my React projects this works like a charm with componentDidMount and componentWillUnmount, and I can prevent memory leaks, but I'm not succeeding to accomplish this in angular.

How could I do this in Angular 5?

Thanks!

Felipe Micali
  • 827
  • 1
  • 11
  • 25
  • 1
    https://juristr.com/blog/2016/09/ng2-event-registration-document/ dont work with the document object – Jota.Toledo Feb 18 '18 at 15:47
  • @Jota.Toledo thank you very much, it solved my problems! With the HostListener decorator I even don't have to worry about removing the event listener when route changes! But now comes another quetion. I noticed that only the immediately next function is triggered for each HostListener declaration. Do you know if it's possible to trigger more than one function for each HostListener? Or should I call all other methods I desire inside this immediately next function? – Felipe Micali Feb 18 '18 at 18:44
  • Also I'd like to know if it's possible to run those HostListeners events conditionally, based on current component config variables. Something like "trigger scroll event only if this.allowScroll === true". Is it possible? Thanks! – Felipe Micali Feb 18 '18 at 19:02
  • Either what you suggest, or decorate the individual methods. Put your conditional logic in the methods... – Jota.Toledo Feb 18 '18 at 19:03
  • 1
    Using @HostListener to manage event listeniners will do it automaticaly for you. – Gilsdav Feb 18 '18 at 21:34
  • @Jota.Toledo thanks again for answering! You are being really helpful! About the conditional listeners, I was thinking about someway to add/remove them conditionally, on demand, so when some condition is not met the event listeners don't exist and the events aren't watched at all, consuming some memory/processing in my application. Do you know if this is possible? Thanks again! – Felipe Micali Feb 19 '18 at 11:00

0 Answers0