How to add click event for dynamically added html element in typescript

I am creating an application in angular 2. I want to add a click event to a dynamically added html element. I am defining a string (contentString), and in this string I am defining an html element.

var contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + '<br/> Click here for more information <button (click)="navigate()">Navigate here</button>'; 

This line is placed inside the html element as follows:

 var boxText = document.createElement("div"); boxText.innerHTML = contentString; 

Although when checking an element it has a certain click event, but it does not fire.

[image 1]

[image 2]

when clicked, a console log follows

 navigate() { console.log("eeeehnnananaa"); } 

But that does not work. Any solution?

+5
source share
1 answer

Angular processes the template when compiling the component. HTML added later is no longer compiled and bindings are ignored.

you can use

 constructor(private elRef:ElementRef) {} ngAfterViewInit() { // assume dynamic HTML was added before this.elRef.nativeElement.querySelector('button').addEventListener('click', this.onClick.bind(this)); } 
+7
source

Source: https://habr.com/ru/post/1265225/


All Articles