I'm still getting used to Angular's change detection implementation, and I'm not clear on whether calling functions in templates causes performance issues.
For example, is it worse to do the following:
<mat-tab-group>
<mat-tab label="First"> {{ getFirstTab() }} </mat-tab>
<mat-tab label="Second"> {{ getSecondTab() }} </mat-tab>
</mat-tab-group>
than do:
<mat-tab-group>
<mat-tab label="First"> {{ firstTabContent }}</mat-tab>
<mat-tab label="Second"> {{ secondTabContent }}</mat-tab>
</mat-tab-group>
What about:
<button *ngIf="shouldShowButton()" .... >
It does: when you use a variable, change detection puts a watch on the variable and the update mechanism fires only when this variable changes.
When you use something more complicated such as a method call, there is no other way than evaluating the expression at each and every change detection cycle and update.
Thus, you are always guaranteed to have equal or (much) better performance with a variable rather than a function call. It all depends on wheter your variable changes a lot or not compared to the number of change detection cycles.
You can find a nice reference in this blog post to dive in the change detection mechanism internals, and here a discussion with examples on your specific question.
Edit after @enno.void comment:
You can use a custom pipe instead in many situations, example is given on this page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With