简体   繁体   中英

Add dynamic HTML from JavaScript in Angular 2/4/5 and bind events

I am trying to add new HTML code via AJAX to an Angular 5 app and add click event to the elements. But the click event doesn't work as expected, I can't use the 2 way data-binding way because I am using the jQuery data-tables plugins and he add the HTML to the Dom and not the angular template.

I have tried:

 <button (click)='myClassFunction()'>Click!</button> this line does nothing <button onclick='myClassFunction()'>Click!</button> this line said myClassFunction is undefined <button onclick='this.myClassFunction()'>Click!</button> this line said myClassFunction is undefined 

How can I bind this click event to my function?

Angular is written in Typescript .

When you serve or build your application, this typescript application is then compiled, minified and uglified to native Javascript .

This means that your

(click)="myClassFunction()"

Will become something along the lines of

onclick="srgu.gferu()"

And as you can see, Angular won't recognize that.

It doesn't matter if you use JQuery or plugins : that is the way Angular works .

To do that, you will need to create window functions , or global functions.

myClassFunction() {
  // Create your window function, make it tslint compliant
  window['myWindowClassFunction'] = () => {
    // Your function's logic here
  };
}

Now, in your appended HTML, you need to write

<button  onclick='window.myWindowClassFunction()'>Click!</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM