Sobes.tech
Middle+

How does the Change Detection strategy OnPush work in Angular? When does a component with OnPush re-render?

sobes.tech AI

Answer from AI

The OnPush change detection strategy in Angular optimizes performance by reducing the number of change detection checks in components.

How OnPush works:

  • Angular checks a component with OnPush only under the following conditions:
    • Input properties (@Input()) of the component have changed by reference (i.e., a new object or primitive has been passed).
    • An event has occurred inside the component (e.g., user input, click).
    • markForCheck() or detectChanges() has been called manually inside the component.
    • An asynchronous event related to Observable or Promise has occurred, if the subscription was made inside the component.

If none of these conditions are met, Angular skips the change detection for the component and its children.

When a component with OnPush is re-rendered:

  • When input data changes by reference.
  • When events occur inside the component.
  • When change detection methods are explicitly called.

This helps avoid unnecessary checks and improves performance, especially in large applications.

How does the Change Detection strategy OnPush work in… - sobes.tech