微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular2 – 在Angular 2中动态添加事件侦听器

早上所有,
我刚刚开始使用Angular 2,我想知道是否有人可以告诉我从元素动态添加删除事件侦听器的最佳方式。

我有一个组件设置。当模板中的某个元素被点击时,我想添加一个监听器mousemove到同一个模板的另一个元素。然后我想删除这个监听器,当第三个元素被点击。

我有种工作只是使用普通的Javascript来抓取元素,然后调用标准的addEventListener(),但我想知道是否有一个更多的“Angular2.0”的方式,我应该研究。

干杯任何建议:)

angular2的方式是使用listen或listenGlobal从 Renderer

例如,如果要向组件添加一个单击事件,则必须使用Renderer和ElementRef(这也为您提供了使用ViewChild或检索nativeElement的任何选项)

constructor(elementRef: ElementRef,renderer: Renderer) {

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

你可以使用listenGlobal,让你访问文档,正文等。

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

注意,因为beta.2都listen和listenGlobal返回一个函数删除侦听器(见beta001的changelog中的breaking changes部分)。这是为了避免大型应用程序中的内存泄漏(参见#6686)。

所以要删除我们动态添加的侦听器,我们必须将listen或listenGlobal赋值给一个将保存函数的变量,然后执行它。

// 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,(event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document',(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。该示例包含listen和listenGlobal的用法

更新

plnkr更新到beta.12和我改进的答案和plnkr,以更清楚如何删除侦听器。

原文地址:https://www.jb51.cc/angularjs/146426.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐