Search code examples
angulartypescriptangular-routing

Javascript removeEventListener OnDestroy not working in Angular 6


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?

attempt 2

    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


Solution

  • Store the callback:

    private visibilityChangeCallback: () => void;
    
    ngOnInit() {
        this.visibilityChangeCallback = () => this.handleVisibleState();
        document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
    }
    
    ngOnDestroy() {
        document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
    }