简体   繁体   English

如何将Angular 4(单击)事件绑定到动态创建的div

[英]How to bind an Angular 4 (click) event to a dynamically created div

The following section of code creates a div block for me. 以下代码部分为我创建了一个div块。

var addOns = '';
addOns = '<div class="divcl"><i class="fa fa-refresh" id="'+self.data.id+'" (click)="addTab($event)"></i></div>';
return "<div class='node' id='"+this.data.id+"'>"+addOns+"</div>";

But it turns out that addTab(event) function is not being recognised by Angular. 但是事实证明,Angular不能识别addTab(event)函数。 My question is how do I bind an Angular click event to a dynamically created div. 我的问题是如何将Angular click事件绑定到动态创建的div。

What you can do is to create an actual HTMLElement and add an eventListener to it and then use appendChild to add it to the DOM. 您可以做的是创建一个实际的HTMLElement并向其中添加一个eventListener,然后使用appendChild将其添加到DOM中。

let addOns = document.createElement('div');
addOns.className ="divcl";
addOns.innerHTML = '<i class="fa fa-refresh" id="'+this.data.id+'"></i>';
this.renderer.listen(addOns, 'click', (event) => {
  this.addTab(event);
})

let node = document.createElement('div');
node.className = 'node';
node.id = this.data.id;
node.appendChild(addOns)

document.querySelector('#stuff').appendChild(node);

https://stackblitz.com/edit/angular-7dffje?file=app%2Fapp.component.ts https://stackblitz.com/edit/angular-7dffje?file=app%2Fapp.component.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM