简体   繁体   中英

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

The following section of code creates a div block for me.

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. My question is how do I bind an Angular click event to a dynamically created 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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