In the third part of our tutorial series on Change Detection in Angular, we will be focusing on the OnPush change detection strategy. OnPush is one of the available change detection strategies in Angular and it can help improve the performance of your application by reducing the frequency of change detections.
What is OnPush Change Detection Strategy?
OnPush is a change detection strategy in Angular that allows you to manually trigger change detection on a component based on certain conditions. By default, Angular uses the default change detection strategy which checks for changes on every component and its children every time a change occurs in the application.
With OnPush strategy, Angular will only check for changes in a component if one of the following conditions is met:
- The input properties of the component have changed
- Events or observables that the component subscribes to emit an event
- Change detection is manually triggered using ChangeDetectorRef
By using OnPush strategy, you can optimize the performance of your application by reducing the number of unnecessary change detections.
How to Implement OnPush Change Detection Strategy
To implement OnPush change detection strategy in your Angular application, follow these steps:
-
Set ChangeDetectionStrategy to OnPush in Component Metadata:
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class MyComponent { // Component logic }
-
Use @Input Decorator for Input Properties:
To trigger change detection in a component using OnPush strategy, you need to update the input properties of the component. Use @Input decorator to define input properties in your component:@Input() myInputProperty: any;
-
Use Immutable Objects:
When using OnPush strategy, it is recommended to use immutable objects for input properties. Immutable objects cannot be changed once they are created, which makes it easier for Angular to detect changes in the component. -
Emitters and Observables:
If your component subscribes to events or observables, make sure to use Emitters or Observables to trigger change detection in the component. -
Manually Trigger Change Detection:
If you need to manually trigger change detection in a component using OnPush strategy, you can inject ChangeDetectorRef in the component and call detectChanges() method:import { ChangeDetectorRef } from '@angular/core'; constructor(private cdr: ChangeDetectorRef) {} triggerChangeDetection(): void { this.cdr.detectChanges(); }
Benefits of OnPush Change Detection Strategy
Using OnPush change detection strategy in your Angular application can provide several benefits:
- Improved performance by reducing the number of unnecessary change detections
- Better control over change detection in components
- Encourages the use of immutable objects for input properties
- Allows for manual triggering of change detection when needed
In conclusion, OnPush change detection strategy is a powerful tool that can help optimize the performance of your Angular application. By following the steps outlined in this tutorial, you can implement OnPush strategy in your components and improve the overall efficiency of your application.
Good note by @ilnurryazhapov9377. The markForCheck() is being called automatically not only when native JS events are handled (e.g. click, scroll, etc) but also happens when the output event (@Output() + EventEmitter) is handled. I had to mention that explicitly but somehow missed that 🙂
💡 Short Frontend Snacks, tips, and news every week here:
Twitter – https://twitter.com/DecodedFrontend
Instagram – https://www.instagram.com/decodedfrontend
LinkedIn – https://www.linkedin.com/in/dmezhenskyi
Finally found the life saver one for OnPush , subscribed!
Please try to bit louder bro
I think difference between view checking and binding checking was not properly explained. I still dont understand
11:09 i dont understand, if all components have onPush, at what point input bindings are checked for changes?(а ты знаешь русский)
Second video of you that I’m watching, you have a great talent making things easy to understand 👌🏼
Really a great tour under the angular hood.
good job mate
doesn't settimeout automatically call change detection ? also doesn't onpush prevent Change detection cycle in child components ? if not what is benefit of using it for performance perspective ?
很棒的讲解!!👍
Probably I missed that information, but when do we need to call markForCheck() manually?
Hi @DecodedFrontend
Whould you mind creating some best practices of using onPush strategy?
Great explanation. Would be perfect if you have source code demonstrates all scenarios.
Thanks for the explanation! Angular change detection happens depth first (animations are showing breadth-first), but I got the whole idea on how the process works. Kudos
Nice vidéo ! I always wonder when should I use OnPush or let the default detection strategy?
Best Advanced Angular tutorials in the world. Thank's to you. Bought your course about forms.
Thanks ❤
Very interesting !
Hi, at 12:48 `<app-slide>` should be inside GalleryComponent not AppComponenent to me. Thank you for this great explanation.
Love from India 🙂
Very well explained!!!