Optimizing Angular Performance: Change Detection Strategy OnPush vs Default

Dinesh Rawat
calendar_month
March 12, 2024
timer
3 min
read time

Understanding Angular's Change Detection:

Angular is smart enough to keep your app's view and data (model) in sync. It does this through something called change detection. Picture it like a superhero that notices any changes you make in your app and quickly reflects them on the screen.

Two Cool Strategies in Angular:

Default Change Detection:

  • What it does: Checks everything in your app, making sure any change gets instantly shown on the screen. In this approach, Angular systematically traverses each component and its children (from top to bottom) in the UI tree during every change detection cycle. It ensures that the view is re-rendered if there are updates in the model.

This default strategy is effective when the entire application needs consistent and thorough monitoring.

Example:



// Angular Component
export class DefaultChangeComponent {
  message: string = 'Hello, Angular!';

  updateMessage() {
    this.message = 'Angular Magic Happened!';
  }
}



{{ message }}

OnPush Change Detection Strategy:

  • What it does: Smarter and faster! Rather than scanning the entire app whenever changes occur, the OnPush change detection strategy selectively checks only the necessary elements. This means the component and all its children will be excluded from the regular change detection cycle, making your app run smoother and faster.

Example:


// Angular Component with OnPush
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: '

{{ message }}

', }) export class OnPushComponent { @Input() message: string = 'Hello, Angular!'; updateMessage() { this.message = 'Angular Magic Happened!'; } }

This will only be inspected when specific conditions arise:

  • When the component's input changes,
  • When an observable with an async pipe emits a value,
  • When manually triggered,
  • When HTML template events are emitted.

Quick Tips:

  • Ensure all your components use the OnPush strategy for maximum efficiency.
  • Simply applying OnPush to a few components won't yield significant improvements. A comprehensive application is required.

Selecting the appropriate strategy can make your Angular app run efficiently. At Shorter Loop, we've observed significant improvements by implementing the OnPush strategy.

Ready to make your Angular journey awesome? Happy coding! 🚀

At Shorter Loop, we focus on making our apps fast and easy to use. Right now, we're looking into a feature of Angular called "change detection strategies". This feature could make our apps react faster to what users do. Even though Angular is already good at detecting changes, we think there's room to make it even better, especially for bigger apps.