且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态地添加角事件监听器2

更新时间:2022-12-27 11:09:11

angular2方式的是使用 listenGlobal 通过渲染

例如,如果你想要一个click事件添加到一个组件,你必须使用渲染和ElementRef(这给你,以及使用ViewChild检索的选项,或任何的 nativeElement

For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement)

constructor(elementRef: ElementRef, renderer: Renderer) {

    // Listen to click events in the component
    renderer.listen(elementRef.nativeElement, 'click', (event) => {
      // Do something with 'event'
    }
);

您可以使用 listenGlobal ,这将让您使用文件

You can use listenGlobal that will give you access to document, body, etc.

renderer.listenGlobal('document', 'click', (event) => {
  // Do something with 'event'
});

请注意,由于beta.2既 listenGlobal 返回函数删除监听器(见重大更改部分从更新日志为beta.2)。这是为了避免在大的应用程序的内存泄漏(见#6686 )。

Note that since beta.2 both listen and listenGlobal return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).

所以要去除我们动态添加监听器,我们必须指定 listenGlobal 来一个变量,将举行函数返回,然后我们执行它。

So to remove the listener we added dynamically we must assign listen or listenGlobal to a variable that will hold the function returned, and then we execute it.

// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;

// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;

constructor(elementRef: ElementRef, renderer: Renderer) {

    // We cache the function "listen" returns
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
        // Do something with 'event'
    });
}

ngOnDestroy() {
    // We execute both functions to remove the respectives listeners

    // Removes "listen" listener
    this.listenFunc();

    // Removs "listenGlobal" listener
    this.globalListenFunc();
}

下面是一个 plnkr 用一个例子来工作。这个例子包含了使用 listenGlobal

Here's a plnkr with an example working. The example contains the usage of listen and listenGlobal.

plnkr被更新为beta.12和我改善了答案和plnkr做出更清楚如何删除监听器。

plnkr was updated to beta.12 and I improved both the answer and the plnkr to make more clear how to remove the listeners.