Understanding Angular’s Change Detection

If you have worked with Angular for any length of time, you have likely encountered the concept of change detection. Angular automatically keeps the user interface in sync with the underlying application state, so developers rarely need to intervene. However, it is still important to understand what happens behind the scenes and whether we can influence this process.

Although Angular does all the heavy lifting, we should know how it operates and whether we have options to tweak it. The good news is that we can adjust the behavior of individual components, tailoring it to specific needs.

How Change Detection Works

Angular runs a change detection cycle that walks through the component tree and refreshes the view with any updated data. When a value in a component changes, the new value shows up automatically because Angular re-evaluates and re-renders all components from the root down to the leaves. As noted earlier, this default behavior can be customized, and we will look at that next.

Altering the Default Strategy

Angular provides two change detection strategies: Default and OnPush. The Default strategy is the one we just described. With OnPush, we gain finer control over when a component gets re-rendered, and Angular skips updates unless at least one of these conditions is met:

  • The component receives a new value for an @Input property.
  • The template uses an async pipe and the underlying observable emits.
  • An event originates from the component itself or from one of its children.
  • The component is explicitly flagged for change detection.

The first point concerns how @Input values are handed over. If you want the ngOnChanges hook to fire, pass a new object reference rather than mutating the existing one—think of it as treating inputs as immutable. If you modify an object in place, you may find that the component does not refresh under OnPush, and even with the Default strategy, the ngOnChanges hook may not behave as expected.

To wrap things up, we have covered the fundamentals of change detection and how to gain manual control by switching to the OnPush strategy. Future articles will include practical examples and a deeper look into the mechanics. If you found this helpful, feel free to share it or reach out with questions or suggestions.