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.

3
  • 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 Commented Apr 13, 2018 at 21:24
  • 1
    Possible duplicate: stackoverflow.com/questions/35080387/… Commented Apr 13, 2018 at 21:39
  • check out the console log: stackblitz.com/edit/angular-pc7ymb Commented Apr 13, 2018 at 21:55

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.