7

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()" .... >   
Tachy
  • 971
  • 1
  • 9
  • 14

2 Answers2

10

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.

Qortex
  • 7,087
  • 3
  • 42
  • 59
0

the first method is possible as long as you are calling string...and the function should be inside the mat-tab like this:

<mat-tab-group>
  <mat-tab label="First" {{ getFirstTab() }}> </mat-tab>
  <mat-tab label="Second" {{ getSecondTab() }}> </mat-tab>
</mat-tab-group> 

i don't think the last one will even work at all...calling a function in *ngIf will give error

<button *ngIf="shouldShowButton()" .... > 
Ganesh
  • 5,808
  • 2
  • 21
  • 41
taiwo sunday
  • 33
  • 1
  • 8
  • According to this link, you can call a function in ngIf: https://stackoverflow.com/questions/51723214/angular-6-variable-or-method-binding-in-ngif – Tachy Apr 12 '19 at 13:07
  • okay thanks I have seen it. It seems you must return a boolean value. – taiwo sunday Apr 15 '19 at 07:49