angular - 如何在 Angular 中添加事件监听器?
问题描述
我正在使用 Angular 6 编写应用程序,尝试收听 plotly_click 事件(可视化库)。如何设置监听器?
Angular 推荐使用Renderer2
from API > @angular/core。他们提供了一个listen
应该启动事件监听器的函数。但无论如何,这并不是真的有效,我可以在特定的 DOM 元素上收听事件,document | body
但不能在特定的 DOM 元素上收听。还有addEventListener()
来自EventManager
API > @angular/platform-browser 的方法。但我面临同样的问题。
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)
解决方案
您应该在视图初始化之后而不是在onInit()
方法中注册监听器。
ngAfterViewInit() {
this.renderer.listen(this.myDiv, 'click', (event) => console.log("Trying to listen to click event on that DIV"));
}
推荐阅读
- sql - SQL dbo 到自定义架构迁移步骤
- vue.js - Wuxt (Nuxt/Vue) 根据父/子对 v-for 中的项目进行排序
- sql - 将查询结果放入表变量
- php - 打印来自数据库的双字段时的 Laravel 问题
- ios - 控制中心信息未使用 AVSpeechSynthesizer 更新
- amazon-web-services - 创建 S3 存储桶时触发 Lambda 函数
- promise - 带有环回 lb3 的自动更新模型 - 异步陷阱
- angular - 如果输入为空,则隐藏重置按钮
- python - 使用正则表达式递归拆分字符串
- graphql - Apollo GraphQL 客户端查询返回自省结果而不是数据