angularangular2-changedetectionzonezonejschange-detector-ref

Angular - detectChanges does not invoke ngDoCheck()


I'm running cdr.detectChanges() in some nested child (Child1) that has parent and also another nested child component (Child2).

Why if I will run trigger detectChanges method in Child1 component - only ngDoCheck is invoked in Child2 component? Shouldn't it invoke DoCheck in current component (Child1) and DoCheck in Child2? How can I know that current component is also checked?

I prepared small example: https://github.com/michalgrzegorczyk-dev/change-detection

components: (app-child1, app-child2)


Solution

  • This article explains why that happens:

    When change detection is triggered for a particular view/component it does the following operations in the specified order:

    ... 6. calls OnInit and ngDoCheck on a child component (OnInit is called only during first check)

    So in your case when you run child1.detectChanges() Angular will run ngDoCheck hook on the child component, which is child2. One of the reasons it's designed like this is to allow manual control of OnPush logic from the ngDoCheck hook. If a child2 is defined as onPush, and no input bindings have changed, you still can call changeDetectorRef.markForCheck() from ngDoCheck of child2 to mark the component as dirty. So in a way ngDoCheck signals that Angular is about to run check on the child component, where part of the check involves updating input props on child components and updating view bindings on the current component.