This is how to trigger Change Detection manually in Angular

Angular’s default Change Detection does a pretty good job. However sometimes when the component size increases, it is better to change the Change Detection Strategy to OnPush to gain performance. This is how it will be used for a component.

@Component({ 
  selector: 'app-todo-list',
  templateUrl: './todo-list.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ToDoListComponent {
...

With this Angular will not update the component with every change and therefore we have to inform it manually. There are three ways to inform Angular.

1. ApplicationRef.tick()

Using this method we can inform Angular to process and update all the components

constructor(appRef: ApplicationRef) {}
...
myFunction() {
  // do some stuff
  ... 
  // and then tell Angular to perform Change Detection
  appRef.tick();
}

2. NgZone.run(callback)

NgZone is a service that is used by Angular to execute work inside or outside of Angular zone. When the work is executed outside of Angular zone, Angular is not ware of the changes, therefore executing the run method Angular can be informed of the changes.

constructor(private _ngZone: NgZone) {}
...

// Loop outside of the Angular zone
// so the UI DOES NOT refresh after each setTimeout cycle
processOutsideOfAngularZone() {
  this.label = 'outside';
  this.progress = 0;
  this._ngZone.runOutsideAngular(() => {
    this._increaseProgress(() => {
      // reenter the Angular zone and display done
      this._ngZone.run(() => { console.log('Outside Done!'); });
    });
  });
}

3. ChangeDetectorRef.detectChanges()

This method is different than the previous two methods. The first two methods trigger change detection in all components. However, this method is useful when the changes in a component do not affect other components and Angular will only do the changes in the current component and its children. This is therefore better in terms of performance.

constructor(private ref: ChangeDetectorRef) {
}
...

myFunction() {
  // do some stuff
  ...

  // tell Angular to perform the Change Detection
  this.ref.detectChanges();
}

Leave a Reply