This content originally appeared on DEV Community and was authored by Nikhil Dhawan
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:
- Change in input bound property.
- Use of async pipe.
- Event from component or its child.
- 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.
Till then Happy Learning!
Thanks for reading, do provide your feedback.
This content originally appeared on DEV Community and was authored by Nikhil Dhawan
Nikhil Dhawan | Sciencx (2021-06-10T06:20:38+00:00) Change Detection in Angular. Retrieved from https://www.scien.cx/2021/06/10/change-detection-in-angular/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.