Blog>
Snippets

OnPush Change Detection Strategy

Adopt OnPush change detection to optimize Angular's performance by reducing the frequency of component rendering cycles.
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-on-push-component',
  template: `<h1>{{ title }}</h1>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {
  title = 'OnPush Change Detection';
}
This defines an Angular component with OnPush change detection strategy. With OnPush, change detection will only run when a new reference is passed to @Input() properties or if an event originates from the component or its children.
import { Input, Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<p>{{ config.text }}</p>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
  @Input() config: any;
}
This shows a child component with an @Input property which will trigger change detection when a new reference to the 'config' object is provided.
import { ChangeDetectorRef } from '@angular/core';

export class SomeComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  someMethod(): void {
    // ... some operations that change component state
    this.cdr.markForCheck(); // Marks path for check, so change detection will be run in next cycle
  }
}
This snippet shows how to manually request change detection for a component using ChangeDetectorRef in cases where it might not be automatically detected by the OnPush strategy.