DEV Community

loading...
Cover image for Change Detection in Angular
This is Angular

Change Detection in Angular

Nikhil Dhawan
Updated on ・2 min read

Hi Readers, So if you have been using Angular for a while you might have heard of Angular Change detection. Angular handles all the changes which happen for the application on behalf of us even without our interference. In this article, we are going to discuss angular change detection and then how we can manage that manually.

Even if Angular is doing it for we must know how it's working and do we even have ways to modify it. So the answer to later is Yes, we can modify for the component to behave differently based upon our requirement.

How does it works?

So in Angular is there is a change detection cycle that helps render the component tree with the new changes on its own. If there is some value change in the component then you will be able to see the updated value automatically, as Angular re-renders all the components in the component tree from parent to child for us automatically. So as I mentioned earlier we can modify this behavior, let us discuss briefly on this.

Modifying the default behavior

So Angular has 2 ways for Change Detection, the first is OnPush, and the other is Default. Default is what we have touched already. In the OnPush strategy, we have more control over the component re-rendering and Angular also skips re-rendering of the component if certain conditions are not fulfilled which are:

  1. Change in input bound property.
  2. Use of async pipe.
  3. Event from component or its child.
  4. Manually marked components for change detection.

The first point is related to the value for @Input Decorator. So whenever you are passing the value to the Input property just remember to pass a new reference if you want to take advantage of the ngOnChanges hook which is like passing immutable objects always, if you just modify the object directly instead of providing a new copy you may face issues where the component data is not updated in case of OnPush strategy and even if you are Default strategy and using ngOnChanges hook for some purpose that may not work.

So to sum up, here we learned basics about change detection and how we can have custom control over the component when we set its change detection strategy to OnPush. Hope you were able to understand this, in my upcoming articles about change detection will touch base upon some working examples and some deep dive.
If you liked it please share it with your friends or if any suggestions reach me out on Twitter or comment below.
Till then Happy Learning!

Discussion (0)