How to set the default change detection strategy to OnPush
? Can it be set globally somehow?
I want to avoid having to adding this line to every component
@Component({
...
changeDetection: ChangeDetectionStrategy.OnPush,
...
})
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.
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.
Default means that the change detector's mode will be set to CheckAlways during hydration.
Change detection is the process through which Angular checks to see whether your application state has changed, and if any DOM needs to be updated. At a high level, Angular walks your components from top to bottom, looking for changes.
If a component strategy is not configured, it is marked as default. In this strategy, the change detection cycle runs on each and every event that occur inside the Component. Let's look for issues associated with this Default Change Detection Strategy: Given above are 2 Components: ParentComponent and ChildComponent.
What is Change Detection Strategy in Angular ? Angular Change Detection Strategy are the methods by which the updates to the component is tracked and component is triggered to Re-render. There are majorly 2 Change Detection Strategy in Angular.
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:
The first is detectChanges() which tells Angular to run change detection on the component and his children. The second is ApplicationRef.tick() which tells Angular to run change detection for the whole application. The third is markForCheck() which does NOT trigger change detection.
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.
ng generate component test --changeDetection=OnPush
You can also set that value as default in your angular.json, so that you don't need to set the flag every time:
// angular.json
{
//...
"schematics": {
"@schematics/angular": {
"component": {
"changeDetection": "OnPush"
}
}
}
}
The change detection strategy can only be defined per component or directive not globally.
Using a custom decorator is discouraged because it will not be supported by the upcoming offline template compiler.
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