1

If in the views one calls a function on the variable such as:

{{ myFunc(test) }}

This function is executed multiple times rather than 1.

I have it defined my function as:

  myFunc(s: string) {
    console.log("I am being called")
    return s;
  }

and looking at the console log one can see that function is being executed 4 times. Created stackblitz to illustrate.

In my project where function is called from a service I get ~20 console.logs.

Seems very inefficient, why is this happening?

Wagm
  • 309
  • 5
  • 12
  • 1
    It's not at all recommended using function in Angular2+ to bind data, use a variable instead. – Josh Stevens Jul 13 '18 at 07:22
  • This is expected behavior. You should avoid calling functions in expressions. Whatever you are trying to do, there is another way. Further reading: http://spraso.com/functions-in-angular-expressions-are-killing-your-performance/ – JSON Derulo Jul 13 '18 at 07:22
  • 1
    your template gets rendered every time angular assumes you have a change in the state. Every time it renders the template it should recalculate the data it needs to display, so your function is getting called. It is very much logical and correct – smnbbrv Jul 13 '18 at 07:23
  • This is a great article related to what you are asking. [When not to use methods in HTML Templates in Angular](https://blog.appverse.io/why-it-is-a-bad-idea-to-use-methods-in-the-html-templates-with-angular-2-30d49f0d3b16) – Shaurya Dhadwal Jul 13 '18 at 07:26
  • Thanks, this investigation helped me to understand some important points! – Wagm Jul 13 '18 at 07:55
  • @Wagm - Even I learn by answering questions. I also had no idea about this :) – Shaurya Dhadwal Jul 13 '18 at 07:58

0 Answers0