我正在用 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模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)
如何在 ionic2 中的 pop() 之后重新加载离子页面How to reload the ion-page after pop() in ionic2(如何在 ionic2 中的 pop() 之后重新加载离子页面)
当 Ionic 2 中的值发生变化时检索本地存储值Retrieve localstorage value when value is change in Ionic 2(当 Ionic 2 中的值发生变化时检索本地存储值)