简体   繁体   中英

Angular ngOnChanges and the change detection strategies appear to be contradictory?

NgChanges on runs on input bindings - if the input is a reference type - when the reference changes. Ie an object like this:

{ value: 2 }

will not cause ngchanges to run if its value property is changed. This is because the Angular default change detection strategy compares the references.

Angular2 change detection: ngOnChanges not firing for nested object

However this appears to be contradictory to me when we think about the two change detection strategies:

Default - change detection for component happens when bindings change - but according to above this doesnt recognise changes on inputs where the reference type's reference hasnt changed. Or in other words change detection runs only when value type value changes or reference type reference changes.

OnPush - change detection runs only value type value changes or when a reference changes.

Clearly default change detection doesnt work like I understand it to or it would be the same as OnPush, yet the onChanges lifecycle hook seems to only fire under the same rules as OnPush.

Angular will always compare the references of the previous and the new input values. The difference between the Default and the OnPush strategy is when Angular triggers the change detection.

With the Default strategy Angular does dirty checking, that means that it will check every time if something has changed in your application: it will perform checks for each browser event, any HTTP call, timers.... In big applications this approach has a big impact on performance.

With the OnPush change detection, Angular will only check a component when one of its inputs has changed (it relies on the concept of immutability to know when a component changes).

If you want to dive deeper on Angular Change Detection I would suggest you to read this article written by Max Koretskyi, who explains how Change Detection works in deep.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM