Angular - A better way for ChangeDetection (ChangeDetectionStrategy.OnPush)

When we would like to update our template by binding to a method, it will get called every time the app updates which is incredibly inefficient.

For example,

@Component({
    selector: "app-people",
    template: "<p *ngIf="someCondition"></p>"
})
export class People {
	get someCondition(){
		return false;
	}
}

the "someCondition" method will get evaluated every time the app updates.

To resolve this, we could use the ChangeDetectionStrategy.OnPush which only updates our component if one of the three following occurs:

  1. The input reference changes
  2. An event originated from the component or one of its children.
  3. We run change detection explicitly.
@Component({
  // ...
  changeDetection: ChangeDetectionStrategy.OnPush,
})

See here for a more in-depth dive in

References