OnPush helps Angular update components only when needed. This makes apps faster by reducing unnecessary work.
When to use OnPush in 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.
data input changes.import { Component, Input, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-simple', template: `<p>{{ data }}</p>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class SimpleComponent { @Input() data!: string; }
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++; } }
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.
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!'; } }
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.
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.