0
0
Angularframework~5 mins

When to use OnPush in Angular

Choose your learning style9 modes available
Introduction

OnPush helps Angular update components only when needed. This makes apps faster by reducing unnecessary work.

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

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

Set changeDetection to ChangeDetectionStrategy.OnPush inside the @Component decorator.

This tells Angular to check for changes only when input properties change or events happen inside the component.

Examples
Component updates only when data input 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;
}
Component updates on button click because event triggers change detection.
Angular
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-click',
  template: `<button (click)="onClick()">Click me</button>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ClickComponent {
  count = 0;
  onClick() {
    this.count++;
  }
}
Sample Program

This example shows a child component using OnPush. It updates only when the input message changes. Clicking the button changes the text and triggers update.

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;
}

@Component({
  selector: 'app-root',
  template: `
    <app-message [message]="text"></app-message>
    <button (click)="changeText()">Change Text</button>
  `
})
export class AppComponent {
  text = 'Hello';

  changeText() {
    this.text = 'Hello, Angular!';
  }
}
OutputSuccess
Important Notes

OnPush works best when data is immutable or replaced with new objects.

Changing object properties without replacing the object may not trigger updates.

Events inside the component still trigger change detection with OnPush.

Summary

OnPush improves performance by limiting when Angular checks for changes.

Use it when your component relies on inputs or internal events.

Remember to update inputs immutably to see changes reflected.