html - 如何将点击事件添加到 typescript 中动态添加的html元素

标签 html angular typescript ionic2

<分区>

我正在用 Angular 2 构建一个应用程序。我想向动态添加的 html 元素添加一个点击事件。 我定义了一个字符串 (contentString),并在这个字符串中定义了 html 元素。

var contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + '<br/> Click here for more information <button (click)="navigate()">Navigate here</button>'; 

这个字符串被放在这样的 html 元素中:

var boxText = document.createElement("div");
    boxText.innerHTML = contentString;

虽然当我检查元素时,它定义了点击事件,但它没有触发。

[image 1]

[image 2]

点击它应该控制台日志

navigate() {
console.log("eeeehnnananaa");
}

但这行不通。 任何解决方案?

最佳答案

Angular 在编译组件时处理模板。以后添加的 HTML 不再编译,绑定(bind)将被忽略。

你可以使用

constructor(private elRef:ElementRef) {}

ngAfterViewInit() {
  // assume dynamic HTML was added before
  this.elRef.nativeElement.querySelector('button').addEventListener('click', this.onClick.bind(this));
}

关于html - 如何将点击事件添加到 typescript 中动态添加的html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692780/

相关文章:

javascript - 如何在 HTML 页面加载 + Bootstrap 时淡出消息

javascript - 为什么单击 div 时 document.execCommand 不起作用?

html - 与常规页面设计不同的 WordPress 登陆页面

javascript - 如何在 Ionic 3 中打开文档 (.doc .ppt .pdf .xlsx)?

javascript - 对组件的@Input 进行严格的类型检查

angular - 如何设置表单字段值ng-Bootstrap模型的值

javascript - typescript 错误 : Property '0' is missing in type

html - &lt;header&gt; 标签仅在 < 980px 时将内容下移 60px?

javascript - 检测组件内模型数据的变化

reactjs - 在 typescript 中将 useState 作为 props 传递