Marley Marley - 2 months ago 43
TypeScript Question

Removing EventListener in ngOnDestroy

I have the following implementation of a directive. How to removeEventListener in this case:

import { Directive, ElementRef, OnDestroy } from "@angular/core";

@Directive({
selector: "[Enter]"
})
export class Enter implements OnDestroy{
constructor(el: ElementRef) {
let enter = function(event){
if(event.keyCode === 13){
el.nativeElement.click();
}
}
document.addEventListener('keyup', enter , false);
}

ngOnDestroy(){
document.removeEventListener('keyup', enter, false); //this line doesn't work because I can't access enter variable here!
}
}


I know I can simply use a global variable here and can access it. But I don't want to store the state of instance in the global variable.

Answer

Make it like this:

import { Directive, ElementRef, OnDestroy } from "@angular/core";

@Directive({
    selector: "[Enter]"
})
export class Enter implements OnDestroy{

    private enter: (event: KeyboardEvent) => void;

    constructor(el: ElementRef) {
        this.enter = (event) => {
            if(event.keyCode === 13){
                el.nativeElement.click();
            }
        }
        document.addEventListener('keyup',  this.enter , false);
    }

    ngOnDestroy(){
        document.removeEventListener('keyup', this.enter, false);
    }
}