問題描述
我正在用 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模板網!