I am trying to removeEventListener
in my angular compenent: Javascript removeEventListener not working
...
ngOnInit() {
document.addEventListener('visibilitychange', () =>this.handleVisibleState(), true);
}
ngOnDestroy() {
document.removeEventListener('visibilitychange', () => this.handleVisibleState(), true);
}
handleVisibleState() {
let vis = document.visibilityState === 'visible';
this.configsService.update_collab_visible(vis);
}
...
with the above addEventListener
works even after ngOnDestroy ()
How can I unbind visibilityState from document in angular components?
private visibilityChangeCallback: () => void;
ngOnInit() {
this.visibilityChangeCallback = () => this.handleVisibleState();
document.addEventListener('visibilitychange', this.handleVisibleState, true);
}
ngOnDestroy() {
document.removeEventListener('visibilitychange', this.handleVisibleState, true);
}
handleVisibleState() {
let vis = document.visibilityState === 'visible';
console.log(typeof this.configsService); // undefined
this.configsService.update_collab_visible(vis);
}
result:
ERROR TypeError: Cannot read property 'update_collab_visible' of undefined
Store the callback:
private visibilityChangeCallback: () => void;
ngOnInit() {
this.visibilityChangeCallback = () => this.handleVisibleState();
document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
}
ngOnDestroy() {
document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
}