Blog>
Snippets

Reducing Change Detection Cycles with OnPush Strategy

Illustrate how to use the OnPush change detection strategy in Angular components to reduce CPU usage on mobile by minimizing unnecessary change detection.
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';

@Component({
  selector: 'app-on-push-component',
  template: `
    <div>{{ value }}</div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {
  @Input() value: string;
}
This is an Angular component that uses the OnPush change detection strategy. This strategy tells Angular to check for updates to @Input properties of the component only when the reference of the input property changes. This can significantly reduce change detection cycles, especially in components that don't change often or rely on inputs infrequently updated.
import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-manual-check-component',
  template: `
    <button (click)="updateValue()">Update Value</button>
    <app-on-push-component [value]="value"></app-on-push-component>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ManualCheckComponent {
  value = 'Initial value';

  constructor(private cdr: ChangeDetectorRef) {}

  updateValue() {
    this.value = 'Updated value';
    this.cdr.detectChanges(); // Manually trigger change detection
  }
}
This component demonstrates how to manually trigger change detection when using the OnPush change detection strategy. When the `updateValue` method is called, the `value` property is updated, and 'detectChanges()' is called on the injected `ChangeDetectorRef` to inform Angular that it should check the view for updates. This is necessary because Angular by itself won't detect changes in OnPush components unless the reference to an @Input property changes.