1

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?

3
  • 1
    Please use (click) instead of onClick in Angular Commented Jan 16, 2018 at 14:49
  • for angular i think its on-click Commented Jan 16, 2018 at 14:51
  • i tryied (click) Commented Jan 16, 2018 at 14:54

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

unfortunately i had to do it with some jquery but your answer is correct we cant do it in angular ):
Well I just explained you how you can do it, so yes it's possible :D But great if you succeed ! (Using JQuery with Angular is an anti-pattern though)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.