如何添加click事件以在typescript中动态添加html元素

Thi*_*man 11 html typescript ionic2 angular

我正在以角度2构建应用程序.我想在动态添加的html元素中添加click事件.我定义了一个字符串(contentString),在这个字符串中我定义了html元素.

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

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

var boxText = document.createElement("div");
    boxText.innerHTML = contentString;
Run Code Online (Sandbox Code Playgroud)

虽然当我检查元素时,它已定义了click事件,但它没有触发.

[图片1]

[图片2]

点击它应该控制台日志

navigate() {
console.log("eeeehnnananaa");
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.谁有解决方案?

Gün*_*uer 14

Angular在编译组件时处理模板.之后添加的HTML不再编译,并且将忽略绑定.

您可以使用

constructor(private elRef:ElementRef) {}

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


小智 6

就我而言,我会这样做——

var boxText = document.createElement("div");
const contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + 
'<br/> Click here for more information ';//as per your code

boxText.innerHTML = contentString;

const button = document.createElement('button');
button.addEventListener('click', (e) => {
    this.navigate();//your typescript function
});
button.innerText = 'Navigate here';
boxText.appendChild(button);
Run Code Online (Sandbox Code Playgroud)