Have you ever heard of ngDoCheck hook before ? If you do know congrats because most of people doesn’t even know such hook exist in Angular including me 😀 I just discover couple years ago and get shocked because I never heard of it before. But no worries today we will dig into this hook and discover its calabilities.
What ngDoCheck Hook Does ?
In angular whenever change detection mechanism run, it triggers both ngDoCheck and ngOnChanges hooks. It help us to run our own change detection mechanism in a component environment. Some time we go out of the angular zone and default change detection mechanism is not enough to observe every changes in the component. In such cases we can rely on ngDoCheck hook.
You might need to consider triggered every time when the default change detection mechanism run, so if you setup a logic that also triggers default change detection you may end up with infinite cycle that crush your component.
When to Use ngDoCheck Hook ?
1. Debugging
Since ngDoCheck runs every time detection mechanism triggered you can effectively debug your component that if everything works fine as it supposed to.
2. Custom Change Detection
If you have nested objects or arrays in the component that you partially update, you might need to add your own mechanism to react these changes. You can also setup some animations, notifications etc.. based on changes happen in your component state.
3. Third Party Library Integration
If you are using third party library that run outside of the angular ecosystem, you can use ngDoCheck persist component state to library when ngDoCheck hook triggered.
When Not to Use ngDoCheck Hook ?
1. When There Is Angular Alternative
If you can solve your problem by calling change detection manually or there is another solution provided by angular, you should always rely on these solutions. Since ngDoCheck runs for every single change detection cycle you may end up with dozen of side effects or performance problems.
2. When Operations Cost Lots of Resource
If you are running a custom logic that uses to much resource and memory, you may consider for alternative solutions rather than ngDoCheck hook to avoid sirious performance problems.
Conclusion
Overall ngDoCheck is a powerfull mechanism to debug your component or persist component state to third party libraries run outside of Angular. In the other hand very dangerous hook considering that its called frequently. When you need to use ngDoCheck always double check if you actually needed it and there is no other way.