Implementing OnPush Change Detection Strategy in Angular Pt.3

Posted by


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:

  1. 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
    }
  2. 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;
  3. 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.

  4. 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.

  5. 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.

0 0 votes
Article Rating
47 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@DecodedFrontend
1 month ago

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

@deepaks7053
1 month ago

Finally found the life saver one for OnPush , subscribed!

@rishavharsh6520
1 month ago

Please try to bit louder bro

@pashabiceps95
1 month ago

I think difference between view checking and binding checking was not properly explained. I still dont understand

@pashabiceps95
1 month ago

11:09 i dont understand, if all components have onPush, at what point input bindings are checked for changes?(а ты знаешь русский)

@robertaliaj4908
1 month ago

Second video of you that I’m watching, you have a great talent making things easy to understand 👌🏼

@zurajeladze4440
1 month ago

Really a great tour under the angular hood.

@artstar991
1 month ago

good job mate

@geekybruce4819
1 month ago

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 ?

@sayhellotothecat30
1 month ago

很棒的讲解!!👍

@Monkey-on7iz
1 month ago

Probably I missed that information, but when do we need to call markForCheck() manually?

@NikolaGolijanin-m8s
1 month ago

Hi @DecodedFrontend
Whould you mind creating some best practices of using onPush strategy?

@phugia963
1 month ago

Great explanation. Would be perfect if you have source code demonstrates all scenarios.

@nicoscarpa
1 month ago

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

@antoine1003
1 month ago

Nice vidéo ! I always wonder when should I use OnPush or let the default detection strategy?

@ИванСветлов-з1я
1 month ago

Best Advanced Angular tutorials in the world. Thank's to you. Bought your course about forms.

@aravindreddy1792
1 month ago

Thanks ❤

@tarasshevchuk8477
1 month ago

Very interesting !

@muratcanoguzhan
1 month ago

Hi, at 12:48 `<app-slide>` should be inside GalleryComponent not AppComponenent to me. Thank you for this great explanation.

@AmanGupta-oq6qd
1 month ago

Love from India 🙂
Very well explained!!!