Home > Blockchain >  If I shouldn't use functions within my Angular template, why does it seem to be okay to use for
If I shouldn't use functions within my Angular template, why does it seem to be okay to use for

Time:10-05

I am a bit confused about when it is/isn't okay to use functions within an Angular template.

I've seen in many places within the Angular documentation that they use functions like .hasError or .get from the reactive forms module within the template.

Why isn't this a concern? If .get and .hasError isn't a concern, is it okay to use things like .includes within the Angular template as well?

This is a bit of a tangent, but I'm trying to use the [checked] property on a checkbox, and the straight forward way would be to call Array.includes within the [checked] attribute, but I assume this is incorrect? How else can I do it without having to store a bunch of redundant variables? Would the correct approach be to create an includesPipe? If so, why isnt this something that is built into Angular?

CodePudding user response:

As explained in the comments, it depends on the function.

Say you have those two functions :


lightFn() {
  return true;
}

heavyFn() {
  for (const x of new Array(1000).fill(0)) console.log('hey');
  return false;
}

The light function has 1 instruction, the heavy function has at least 1000 instructions.

When you start using Angular, the change detection is ran very often (almost everytime you move your mouse).

This leads in a lot of function calls.

If your function is light, then it's not an issue. Taht's why you can for instance use getters, or built-in function like control.hasError.

THat's why people say to not use functions in templates : it's easier than explaining everything. I do it myself with newcomers, unless like you, they ask for explanation.

There are several solutions to be able to use heavy functions directly in HTML :

  • Use the onPush change detection : change detection gets reduced A LOT, hence you do much less function calls
  • Use a pipe : pipes are pure at first, this means they are ran only when the input provided to it changes. Just be sure not to trigger it too often !
  • Use some state management : The heavy computation is only ran when the state changes, and your template does not have to call the heavy function at every change detection.
  • Simplify your code : most of the time, you do not have to call a heavy function into your template. This is a good exercise to improve your overall code quality and your issue resolving skills. By far my most appreciated one !

Helping all of this helps you, if not, feel free to ask for more information !

  • Related