html – (click) event not work in innerHtml string Angular 4-ThrowExceptions

Exception or error:

My function isn’t called when I click the <a... tag.

I have the following code in my component:

public htmlstr: string;
public idUser:number;

this.idUser = 1;
this.htmlstr = `<a (click)="delete(idUser)">${idUser}</a>`;

public delete(idUser){
    alert("id " + idUser);
}

My html

<div [innerHTML]="htmlstr"></div>

but the function delete isn’t called and does not show the alert.

The <div... is created dynamically

How to solve:

If anyone face same issue and above all answer not working then try my trick :

In HTML :

<button onclick="Window.myComponent.test()"> test </button>

In component :

class 
  constructor(){
    Window["myComponent"] = this;
  }


  test(){
    console.log("testing");
  }

###

Your main issue here, on-top of the things pointed out by @Matt Clyde and @Marciej21592, is that you’re trying to dynamically add HTML code that needs to be compiled before it can be used (you’re trying to bind to a method and variable).

Some ways of doing this can be seen here.

From the code you have supplied, however, there are much easier ways to accomplish what you are after. For starters, I would have that code in the HTML to begin with and hide/show it as needed with ngIf.

###

I assume that it is not a bug but rather Angular’s security measure against XSS attacks – for more information I would suggest taking a look here https://angular.io/guide/security#sanitization-example

I somewhat also fail to understand why you insist on passing the event via string literal instead of just simply using:

<div>
    <a (click)="delete(idUser)">${this.idUser}</a>
</div>

###

Your component has inner Html.
Angular will not allow events inside inner Html portions for security reasons. You can use Child components. to make events from inside of inner Html portions. Create a child component and put your html inside the child component and pass the data by using any angular events between parent and child using Input, Output features in Angular

###

I don’t often use [innerHTML], but it looks like the template string you’re using <a (click)="delete(idUser)">${idUser}</a> is referencing ${idUser} when you might have meant ${this.idUser}?

###

Below code snippet worked for me:-

In component :

ngAfterViewChecked () {

    if (this.elementRef.nativeElement.querySelector('ID or Class of the Html element')) {
      this.elementRef.nativeElement.querySelector('ID or Class of the Html element').addEventListener('click', this.editToken.bind(this));
    }
  }

inside constructor parameter:-

constructor( private readonly elementRef: ElementRef) {}

import { ElementRef } from '@angular/core';---> at the top of the file

implement 'AfterViewChecked' 

Leave a Reply

Your email address will not be published. Required fields are marked *