So what is change detection?
Change detection is a fundamental aspect of Angular, responsible for identifying and updating parts of the DOM that have changed in response to data modifications or user interactions. It runs specific functions in Life Cycle Hook
In Angular, Change Detection is triggered in the following cases:
- When Component (or Directive) initializes, change detection is triggered to render the UI through the ApplicationRef.tick() function
- When an Event Listener is triggered, the DOM updates data in the component and triggers change detection
- When making a data request (using a service to call data from the server), it updates the UI based on new data
- After executing timer function such as setTimeout(), setInterval(), etc.
- When using Promise.then()
- When using asynchronous function such as WebSocket.onmessage(), Canvas.blob(),etc.
Change detection strategy
The strategy that the default change detector uses to detect changes. When set, takes effect the next time change detection is triggered. (You can read it in ChangeDetectionStrategy Enum Document)
As you can see, Angular has two types of change detection strategies:
- Default: This is CheckAlways, where change detection runs automatically based on zone.js to detect changes with asynchronous functions
- OnPush: This is CheckOnce, where change detection runs only once when the component initializes. After initialization, change detection is triggered in two cases:
- When the component’s @Input properties change (changing value for immutable type, or changing reference for mutable type)
- When template events occur, such as onClick, onMouseMove,etc.
So why Angular create the OnPush strategy?
Because the Default Change Detection strategy is always executing and can affect performance, the OnPush strategy is recommended to improve performance as it only runs in two cases mentioned above.
When components use the OnPush strategy, all their children use OnPush strategy too, and Angular prevents overriding children’s strategy to Default strategy.