3
votes

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>
2

2 Answers

0
votes

This is expected behavior.

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

0
votes

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

@Component({
  // ...
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  // ...
}