1
votes

I get HTML string from the server. Inside the HTML string, I added a button with Id, Text and an onclick event and set to innerHTML. On the UI, the button got created with Id and Text but the Onclick event not working in Angular 6.

Solutions Tried:

  1. Created a directive with a button on the template attached the directive inside the dynamic html
  2. Created a Component with button on the template attached the Component inside the dynamic HTML

In both, the above cases the button got created but event listener was not working.

And I googled a lot couldn't find a single working example or concrete solution to provide

Any solutions appreciated

1
I'm not saying it's not possible, but you should not load dynamic HTML inside an angular component. You can make it work by using the compiler and whatnot, but this means you have to include the compiler inside your AOT build project. You should find another way to obtain the HTML (preferably during build), or another way to handle the click - Poul Kruijt
Hi @PierreDuc Thanks for the response.. can u pls give it with a example code or the process how to associate an event with the Dynamic HTML. - Jebin

1 Answers

0
votes

Angular doesn't process HTML added by [innerHTML]="..."

So you can handle your click event like this.

elementRef.nativeElement.querySelector('button').addEventListener(...)