Blog>
Snippets

Implementing OnPush Change Detection Strategy

Showcase how to use the OnPush change detection strategy in Angular to enhance performance.
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-on-push-component',
  template: '<p>{{ data }}</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {
  data: string = 'Initial data';

  // This method is used to manually trigger change detection
  updateData(newData: string) {
    this.data = newData;
    // Since we use OnPush change detection,
    // the view will only update if the reference of the 'data' property changes,
    // which can be achieved by methods like input properties change or manually triggering.
  }
}
This Angular component is using the OnPush change detection strategy, which means it will only check for changes when its input properties change or when it's explicitly told to. This is a more performance-optimized approach, as it reduces the number of checks performed by Angular's change detection process. An updateData method is provided to trigger changes manually when necessary.