Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(click) event not work in innerHtml string Angular 4

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

like image 233
erickterri Avatar asked Feb 15 '18 22:02

erickterri


3 Answers

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");
  }
like image 176
Khurshid Ansari Avatar answered Nov 19 '22 07:11

Khurshid Ansari


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.

like image 44
Simon K Avatar answered Nov 19 '22 08:11

Simon K


i use this method and its work

public htmlstr: string;
public idUser:number;

this.idUser = 1;
this.htmlstr = `<a id='innerHtmlClick'>${idUser}</a>`     
        this.htmlstr.querySelector(`innerHtmlClick`).addEventListener('click', () => {
        this.delete(idUser);
      });

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

EventListener listen the event bye using id of innerHtml

like image 1
Justin J Avatar answered Nov 19 '22 09:11

Justin J