Search code examples
angularangular2-changedetection

Would you recommend ChangeDetectionStrategy.OnPush as default changeDetection in Angular 2?


Would it be a reasonable convention within an Angular-2 project to always use

changeDetection: ChangeDetectionStrategy.OnPush

within a component's decorator? Except when there are clear reasons to use the default-strategy?


Solution

  • Especially for big project, the answer is YES and it is always recommended to add it as first thing when you create new components.

    The reason is simple: 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. Another way is using the async pipe in the view if you are waiting for a subscription value.

    To add automatically the OnPush strategy when running the ng generate component command in the terminal, you just need to add the option in your angular.json at the schematics node:

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