[Fixed] How to add mouseover event to a dynamically generated html element by using setAttribute in angular


I actually want to add (mouseover)="sample()" to some html elements which are generated dynamically when the page loads in the browser

I tried to add the mouseover to the html element by using

const span = document.createElement("span");
  span.className = "highlight";
  span.setAttribute('mouseover', "showToolTip()");

by executing the above code, the mouseover has been added to the dynamic html element in this way :

<span mouseover="showToolTip()">First item</span>

But as I’m using angular I need to wrap the mouseover event with parenthesis, which should look like

<span (mouseover)="showToolTip()">First item</span>

Is there any way to do this?


When using native templates injected in the DOM, angular will not parse these parts and discover the directive for the mouseover event.
I would suggest adding the native mouseover event instead like so

const span = document.createElement("span");
span.className = "highlight";
span.addEventListener("mouseover", ( event ) => {

Edit: After some discutions in the comments we made a more complete solution for OP. Stackblitz here

Leave a Reply

(*) Required, Your email will not be published