3

I noticed using ngIf or ngFor with a function will call the function many times per second. In contrast using a string, number or object it will be checked only when change detection kicks in.

Am i doing something wrong? Or is this the expected behavior? I would say there is no need to check the function again if nothing changed somewhere.

Example:

Component:

myFunction() {
    console.log('I was checked');
    return true;
}

Template:

<div *ngIf="myFunction()">hello there!</div>
Mick
  • 8,203
  • 10
  • 44
  • 66
  • 1
    This looks similar to https://stackoverflow.com/questions/35469024/how-does-angular-2-change-detection-work or https://stackoverflow.com/questions/42661353/angular2-functions-in-template-and-change-detection – 0mpurdy Aug 07 '17 at 14:11
  • Yes it's expected: https://stackoverflow.com/a/43085186/6294072 – AT82 Aug 09 '17 at 13:41

2 Answers2

0

This is expected behavior.

Angular performs a lot of checks per millisecond to detect whether something changed or not.

taras-d
  • 1,789
  • 1
  • 12
  • 29
0

You can use ChangeDetectionStrategy to avoid this. I am no so sure of this.

@Component({
  // ...
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  // ...
}
Sibiraj
  • 4,486
  • 7
  • 33
  • 57