如何将点击事件添加到angular.js中动态创建的锚标记?



我的要求是首先将纯文本的一部分转换为链接,然后将单击处理程序附加到它。点击该链接后,会弹出一个显示详细信息的窗口。

要将正常字符串转换为链接,我使用了下面的代码,但我无法将单击事件侦听器附加到它。

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;

我尝试添加(click)="myMethod"document.getElementById('anchorId").addEventListener('click','myMethod'),但两种方法都失败了。有人能帮帮忙吗?

我在angular中使用ngAfterViewInit找到了解决方案。

public ngAfterViewInit() {
const anchor = this.elementRef.nativeElement.querySelector('#anchorId');
if (anchor) {
anchor.addEventListener('click', () => {
// Do your task
});
}
}

最新更新