0

I am new to angular 4. I have a component which makes an API call. API call returns me some html that has angular 4 code:

(click) = "functionName()".

The problem is functionName is never called

Blauharley
  • 4,186
  • 6
  • 28
  • 47

1 Answers1

1

I don't need to see your code to tell you that what you're doing is wrong.

When you write

(click)="functionName()"

You're not saying

Handle a click event on this tag

You're saying

Please almighty Angular, when you compile my code to native Javascript, could you have the decency to bind an event on the click on this tag ?

(Ok, I've gone too far, but you get the point).

This means in a template, when you write this; it is changed at compilation to

onclick="a()" // It's minified once bundled

So, if your write this in your database, it will not be compiled, meaning it will neither understand what (click) is, nor what functionName represents.

What are your options ?

You could, for instance, write this in your database

onclick="windowFunctionName()"

Instead of what you wrote, and in your component, create a function bound to your window :

ngOnInit() {
  window['windowFunctionName'] = () => { /* ... */};
}

ngOnDestroy() {
  delete(window['windowFunctionName']; // delete it for memory purpose
}
Community
  • 1
  • 1
  • can we not compile the the html, as used to be in angular 1? – imranashake Jan 05 '18 at 09:00
  • No. AngularJS was plain vanilla JS, now you use Typescript : Typescrpit needs to be compiled by your CLI into vanilla JS. this means that if you request something from DB, you code is already compiled, thus nuable to be ran. –  Jan 05 '18 at 09:13
  • Thanks @trichetriche – imranashake Jan 09 '18 at 10:09