我想将点击事件附加到动态创建的 html 元素。单击事件应该能够触发组件中的另一个方法。
我已经浏览过其他建议使用 ElementRef 附加事件的答案。但是,它不适用于我的情况。
我正在使用 mapQuest API 来渲染地图。地图将绘制地理编码并添加滚动内容。为了添加翻转内容,我使用mapQuest的API方法,例如info.setInfoContentHTML('<a>click me</a>');
仅供参考:https://developer.mapquest.com/documentation/javascript-api/pois-infowindows/ https://developer.mapquest.com/documentation/javascript-api/pois-infowindows/
该链接将位于弹出窗口内,当用户将鼠标悬停在图标上时,该链接将由插件动态添加到 dom 中。如何在仅当用户将鼠标悬停在链接上时显示的事件侦听器并且插件没有提供可以在显示悬停弹出窗口后触发的回调事件。
我一直在寻找类似 jQuery live 的功能,尽管该元素不在 DOM 上,但它会附加事件侦听器。
因为 Angular 在编译组件时会处理模板。
稍后添加的任何 HTML 都不会再次编译,并且绑定将被忽略。
您可以使用以下内容:
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
// assume dynamic HTML was added before
this.elRef.nativeElement.querySelector('button').addEventListener('click',
this.onClick.bind(this));
}
您的用例:
public createElement(){
const el = '<button>click me</button>';
this.elRef.nativeElement.querySelector('button').addEventListener('click',
this.methodName.bind(this));
info.setInfoContentHTML(el);
}
public methodName(){
console.log('burrah!!! called');
}
2022 年更新。 :
Stackblitz 演示 https://stackblitz.com/edit/angular-ivy-mcpsw8
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)