Search code examples
angularangular2-changedetection

What does Strategy OnPush mean?


I am new to Angular2 with TypeScript. I am currently working on a project and unfortunately, cannot understand what does OnPush do:

changeDetection : ChangeDetectionStrategy.OnPush

I have searched a lot, but did not find (did not understand) the correct answer.

Can anybody explain it to me? Example could be appreciatable.


Solution

  • On push change detection means that the change detection on the component is run only when the inputs change, and when the inputs change, their whole object must change. What that means is if only the reference changes the change detection will not be run.

    For example if you have an input on a component that is an array:

    @Input() testArray: Item[] = [];
    

    If you modify that array in the parent component with push, change detection will not run on the child component. But if you do something like this:

    array = [...array, newItem];
    
    <test-component [testArray]="array"></test-component>
    

    Change detection will run. This is used to increase your application performance as it greatly reduces the number of times change detection runs. It is normally paired with immutable data structures and especially Redux patterns with store such as @ngrx/store.