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.
Bad:
<tr *ngFor="let user of users">
{{ someFunction(user)}}
</tr>
Good:
Creating a property in the ts file and setting the value to it once.
this.users = this.users.map(user => ({ ...users, firstname: someFunction(user) });
Better:
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.
@Pipe({
name: 'examplepipe',
pure: true
})
export class ExamplePipe implements PipeTransform {
transform(value: any, args?: any): any {
// code here
}
}
Top comments (3)
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.
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?
You have a point, that's right. thanks!, i will create a new topic for that (onPush).