[英]How to add click event to a dynamically created anchor tag in angular.js?
My requirement is to first convert a part of plain text to a link and then attach a click handler to it.我的要求是首先将纯文本的一部分转换为链接,然后为其附加点击处理程序。 On click of that link, a popup should open with some details to show.
单击该链接时,应打开一个弹出窗口,其中显示一些详细信息。
To convert that normal string to a link, I've used below code, but I'm unable to attach a click event listener to it.为了将该普通字符串转换为链接,我使用了以下代码,但我无法为其附加点击事件侦听器。
const arrayLabel = text.split('$');
let stylizedText = arrayLabel[0];
stylizedText += `<a id="anchorId" style="text-decoration: none;" href="javascript:void(0)">${arrayLabel[1]}</a> `;
stylizedText += arrayLabel[2];
return stylizedText;
I tried to add (click)="myMethod"
and document.getElementById('anchorId").addEventListener('click','myMethod')
,but both approaches failed. Can anyone please help here?我尝试添加
(click)="myMethod"
和document.getElementById('anchorId").addEventListener('click','myMethod')
,但这两种方法都失败了。有人可以帮忙吗?
I figured out the solution for this using ngAfterViewInit in angular.我在 angular 中使用 ngAfterViewInit 找到了解决方案。
public ngAfterViewInit() {
const anchor = this.elementRef.nativeElement.querySelector('#anchorId');
if (anchor) {
anchor.addEventListener('click', () => {
// Do your task
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.