How to set the ChangeDetectionStrategy.OnPush as default strategy for every component in my app instead of writing on every component's template changeDetection: ChangeDetectionStrategy.OnPush
?
Thanks
Best Regards Mark Nebrat
default change detection strategy. With this strategy, Angular will have no assumption on the component's dependency and will check every component from the component tree from top to bottom every time an event triggers change detection on browser events, timers, XHRs, and promises.
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.
So how do you implement OnPush strategy for a component? All you need to do is add the changeDetection parameter in their @Component annotation. import {ChangeDetectionStrategy, Component} from '@angular/core'; @Component({ // ... changeDetection: ChangeDetectionStrategy.
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.
It is possible to set the change detection strategy to OnPush in the CLI so that newly generated components will have it set like that. You can also set that value as default in your angular.json, so that you don't need to set the flag every time:
Compared to the default strategy, the onpush strategy mainly revolves around two questions which are: Is there any change in the reference type? If there are changes in the reference of the reference type, then are there any changes in the values of the heap memory?
When using a change detection strategy of OnPush, other than making sure to pass new references every time something should change, you can also make use of the ChangeDetectorRef for complete control. You could for example keep mutating your data, and then have a button in the child component with a Refresh button.
The main idea behind the OnPush strategy manifests from the realization that if we treat reference types as immutable objects, we can detect if a value has changed much faster. When a reference type is immutable, this means every time it is updated, the reference on the stack memory will have to change.
It's not possible to set the global ChangeDetection.
However, it is possible to set it on the CLI, so that all components newly generated using ng generate component
(or ng g c
) will have it set to OnPush
.
Run this command to set it:
ng config schematics.@schematics/angular.component.changeDetection OnPush
Alternatively (this is what this command does), add this block at the base level of your angular.json
:
// angular.json { //... "schematics": { "@schematics/angular": { "component": { "changeDetection": "OnPush" } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With