首页 > 解决方案 > 如何在 Angular 中添加事件监听器?

问题描述

我正在使用 Angular 6 编写应用程序,尝试收听 plotly_click 事件(可视化库)。如何设置监听器?

Angular 推荐使用Renderer2from API > @angular/core。他们提供了一个listen应该启动事件监听器的函数。但无论如何,这并不是真的有效,我可以在特定的 DOM 元素上收听事件,document | body但不能在特定的 DOM 元素上收听。还有addEventListener()来自EventManagerAPI > @angular/platform-b​​rowser 的方法。但我面临同样的问题。

import {... , Renderer2 } from '@angular/core';
import { EventManager } from '@angular/platform-browser';

@Component({
    selector: 'app-abc',
    template: '<div id="myDiv">abcdefghjk</div>',
})

@ViewChild('myDiv') myDiv: ElementRef;

ngOnInit() {
   this.renderer.listen(this.myDiv, 'click', (event) => console.log("Trying to listen to click event on that DIV"));
    // Or i tried also to use the evenetManager method
   this.eventManager.addEventListener(this.button, 'click', (event) => console.log("Trying to listen to click event on that DIV"));
}

这是我得到的错误(使用事件管理器时我得到了同样的错误):

SummaryComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'listen' of undefined
    at SummaryComponent.push../src/app/summary/summary.component.ts.SummaryComponent.ngOnInit (summary.component.ts:21)
    at checkAndUpdateDirectiveInline (core.js:10105)
    at checkAndUpdateNodeInline (core.js:11371)
    at checkAndUpdateNode (core.js:11333)
    at debugCheckAndUpdateNode (core.js:11970)
    at debugCheckDirectivesFn (core.js:11930)
    at Object.eval [as updateDirectives] (SummaryComponent_Host.ngfactory.js? [sm]:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11922)
    at checkAndUpdateView (core.js:11315)
    at callViewAction (core.js:11556)

标签: angulareventsaddeventlistener

解决方案


您应该在视图初始化之后而不是在onInit()方法中注册监听器。

    ngAfterViewInit() {
       this.renderer.listen(this.myDiv, 'click', (event) => console.log("Trying to listen to click event on that DIV"));
    }

推荐阅读