In Angular 2+, ngDoCheck and ngAfterViewChecked seems to perform same function.
ngDoCheck is said to be called whenever change detection is triggered. Now this change detection will be triggered with change in View. As per docs, ngAfterViewChecked is called whenever view changes.
What is the need of two lifecycle hooks here when one was sufficient?
The
DoCheckhook allows you to integrate into the change detection cycle and find changes within the objects references or any areas where Angular did not detect changes automatically. The interface is as follows:depending on the component tree size and complexity, the
ngDoCheckmethod is going to execute enormous amount of times and may become a performance bottleneck if you poorly implement the code. Avoid usingngDoCheckmethod unless necessary.When using properties of the object type, Angular is going to watch the changes by value reference, meaning it detects the change of the entire value, but not the changes in the child properties. That is the case where we are going to use
DoChecklifecycle hook and detect changes in the object.The
ngAfterViewCheckedmethod represents theAfterViewCheckedlifecycle hook and interface. It allows you to provide custom change tracking that is not handled by Angular due to some reason. The behaviour is similar to the AfterContentChecked hook but applies to the view template children rather than projected content.Primarily DoCheck is for your Business Logic changes which will not be detected by angular in scenarios as stated above. The
AfterViewCheckedis for View tracking.Hope that helps!!!