0
0
Angularframework~5 mins

OnPush change detection strategy in Angular

Choose your learning style9 modes available
Introduction

OnPush helps Angular check for changes only when needed. This makes apps faster by avoiding unnecessary work.

When your component gets data only from inputs and does not change it internally.
When you want to improve app speed by reducing how often Angular checks for updates.
When your component shows data that rarely changes or changes only by new inputs.
When you want to control exactly when Angular updates the view.
When building large apps where performance matters.
Syntax
Angular
import { Component, ChangeDetectionStrategy } from '@angular/core';

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

The changeDetection property is set inside the @Component decorator.

Use ChangeDetectionStrategy.OnPush to enable this strategy.

Examples
This component updates only when its input data changes.
Angular
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-simple',
  template: `<p>{{ data }}</p>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SimpleComponent {
  @Input() data!: string;
}
This will NOT update the view after 1 second because the setTimeout callback does not trigger change detection in OnPush unless inputs change or events occur.
Angular
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `<p>Count: {{ count }}</p>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CounterComponent {
  count = 0;

  constructor() {
    setTimeout(() => {
      this.count++;
    }, 1000);
  }
}
Sample Program

This component only updates its displayed message when the input message changes. Angular skips checking it otherwise, improving performance.

Angular
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-message',
  template: `<p>{{ message }}</p>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MessageComponent {
  @Input() message!: string;
}

// Usage in parent component template:
// <app-message [message]="parentMessage"></app-message>

// When 'parentMessage' changes, MessageComponent updates. Otherwise, it does not check for changes.
OutputSuccess
Important Notes

OnPush works best when inputs are immutable or replaced with new objects.

Internal changes inside the component without input changes will NOT trigger view updates.

You can manually trigger change detection if needed using ChangeDetectorRef.

Summary

OnPush makes Angular check for changes only when inputs change or events happen.

This improves app speed by reducing unnecessary checks.

Use OnPush when your component depends mainly on inputs and does not change data internally.