我正在用 Angular 2 构建一个应用程序.我想将点击事件添加到动态添加的 html 元素中.我定义了一个字符串(contentString),在这个字符串中我定义了html元素.
I'm building an app in angular 2. I want to add a click event to a dynamically added html element. I define a string (contentString), and in this string I define the html element.
var contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + '<br/> Click here for more information <button (click)="navigate()">Navigate here</button>';
这个字符串被放在一个像这样的html元素中:
This string is put inside a html element like this:
var boxText = document.createElement("div");
boxText.innerHTML = contentString;
虽然当我检查元素时,它定义了点击事件,但它没有触发.
Although when I inspect the element, it has the click event defined, but it does not trigger.
点击它应该控制台日志
navigate() {
console.log("eeeehnnananaa");
}
但这不起作用.有人解决吗?
But that does not work. Anyone a solution?
Angular 在组件编译时处理模板.以后添加的 HTML 不再编译,绑定被忽略.
Angular processes the template when the component is compiled. HTML added later is not compiled anymore and bindings are ignored.
你可以使用
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
// assume dynamic HTML was added before
this.elRef.nativeElement.querySelector('button').addEventListener('click', this.onClick.bind(this));
}
这篇关于如何将点击事件添加到打字稿中动态添加的html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!