1

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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Ronak Gupta
  • 71
  • 2
  • 8
  • Don't know much about angular or if things work differently there but in plain javascript you could bind event to the parent of that dynamically created `div` and use event delegation via `event.target` – Matus Dubrava Apr 13 '18 at 21:24
  • 1
    Possible duplicate: https://stackoverflow.com/questions/35080387/dynamically-add-event-listener-in-angular-2 – Mathias W Apr 13 '18 at 21:39
  • check out the console log: https://stackblitz.com/edit/angular-pc7ymb – Vega Apr 13 '18 at 21:55

1 Answers1

2

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

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Mathias W
  • 1,433
  • 12
  • 16