本文介绍了在ngOnDestroy中删除EventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我具有以下指令的实现.在这种情况下,如何删除EventListener:

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.

推荐答案

这应该可以解决问题:

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

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

    ngOnDestroy(){
        document.removeEventListener('keyup', this.enter, false);
        console.log("Removed event listener");
    }
}

希望这会有所帮助.

干杯,深圳

这篇关于在ngOnDestroy中删除EventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 05:25