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?


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.


If you are working especially with very big projects, the OnPush strategy is recommended to decrease the change detection process that it is a very expensive operation.

There are many ways of starting the detection when needed, maybe the most used is to trigger manually changeDetection() from the ChangeDetectorRef.

If you have an inherited project and you want to use the OnPush strategy, the recommendation is to start applying it from the leaf components, check that everything is still working, and then follow the ancestors and go up one level at time to the root. In the end the overall performance is going to benefit.

Here there is a very good article about change detection in Angular.

If you want your new generated components to have automatically the OnPush strategy added, you just need to add the option in your angular.json at the schematics node, for example:

...

    "schematics": {
        "@schematics/angular:component": {
            "changeDetection": "OnPush",
            "prefix": "app",
            "styleext": "scss"
        },
        "@schematics/angular:directive": {
            "prefix": "app"
        }
    }
...