如何在Angular中添加事件监听器?

时间:2019-06-25 08:30:49

标签: angular events addeventlistener

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

Angular建议使用API​​> @ angular / core中的Renderer2。 它们提供了listen函数,该函数应该启动事件侦听器。但是,无论如何这都不是真正有效的方法,我可以监听document | body上的事件,但不能监听特定的DOM Element。 API> @ angular / platform-b​​rowser中还有addEventListener()中的方法EventManager。但是我面临着同样的问题。

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)

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

另一个选择是RxJS fromEvent创建运算符

fromEvent(this.host.nativeElement, 'wheel')  // here you can use any DOM element
   .pipe(
       throttleTime(150),
       takeUntil(this.onDestroy$),  // don`t forget to cleanup!      
       tap((e: WheelEvent)=> this.doFancyStuff(e.deltaY))
   ).subscribe()