Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always use ChangeDetectionStrategy.OnPush

Should I always use ChangeDetectionStrategy.OnPush in my components?

I always hear how OnPush is absolutely amazing, and solves so many issues, speeds up the Angular app, and even get rid of NgZone. But if it is, why isn't it generated by default with ng g component?

If it is so amazing, then should we always use it?

like image 439
Dolan Avatar asked Oct 25 '18 00:10

Dolan


People also ask

What is the use of ChangeDetectionStrategy OnPush?

The Effect of OnPush The OnPush strategy changes Angular's change detection behavior in a similar way as detaching a component does. The change detection doesn't run automatically for every component anymore.

What is the difference between OnPush and default change detection?

OnPush means that the change detector's mode will be set to CheckOnce during hydration. Default means that the change detector's mode will be set to CheckAlways during hydration.

What is the default component change detection strategy in Angular?

By default, Angular 2+ performs change detection on all components (from top to bottom) every time something changes in your app. A change can occur from a user event or data received from a network request.


1 Answers

why isn't it generated by default with ng g component?

It is a design decision that developer needs to make. ChangeDetectionStartegy.OnPush works well with immutable objects. If you don't use immutable objects, you will be having hard time finding what's going wrong with your component. Since the angular team doesn't force you to use immutable objects why would they generate component with this strategy.

You can read more on ChangeDetection here: Everything you need to know about change detection in Angular

OnPush is designed to work with the components that have @Input() decorators. In simple words components that take inputs from their parent component. Since change detection is an expensive operation you can configure such components to run change detection only when their input property changes.

A good example for OnPush() to be used would be a loader component.

like image 91
Ritesh Waghela Avatar answered Sep 24 '22 12:09

Ritesh Waghela