DEV Community

Cover image for Angular - Avoid function calls in templates
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on • Updated on

Angular - Avoid function calls in templates

It is not a good practice to write function calls for computing values inside the templates.

Angular will run your function in each of it's change detection cycle (which is quite frequent) and if the function is a complex one, this will impose a serious effect on the performance.


<tr *ngFor="let user of users">
  {{ someFunction(user)}}
Enter fullscreen mode Exit fullscreen mode

Creating a property in the ts file and setting the value to it once.

this.users = => ({ ...users, firstname: someFunction(user) });

Enter fullscreen mode Exit fullscreen mode

Angular Pipes - A pure pipe is a pipe that will always return the same output for an input. Angular executes a pure pipe only when it detects a pure change to the input value because it already knows that the pipe will return the same value for the same input.

     name: 'examplepipe',
     pure: true
export class ExamplePipe implements PipeTransform {
     transform(value: any, args?: any): any {
          // code here
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

abdurrkhalid333 profile image
Abdur Rehman Khalid

This is a good implementation of the function calls in the templates but it depends upon the need of the function calls in the angular templates for example let's say that you are trying to calculate the total price for the items in the bucket so what you will do is to call the function in order to get the total price whenever the product is removed or added into the basket. So, it all depends upon the need and use case of the coding. But again as far as possible we should try not to use the function calls on the template.

fyodorio profile image

I guess the tradeoffs of calling component’s methods in templates are mitigated if you use on-push change detection strategy inside simple purely presentational components, right?

sandrocagara profile image
Sandro Jhuliano Cagara • Edited

You have a point, that's right. thanks!, i will create a new topic for that (onPush).