Why is change detection called twice?

7.2k Views Asked by At

I have a simple test-component with no logic. I render this component. Why is the DoCheck hook called twice?

So far I understand, DoCheck is called for every change detection. But there is no change. I just render the component and DoCheck is already called two times. Also ngAfterContentChecked and ngAfterViewChecked.

enter image description here

3

There are 3 best solutions below

0
On

ngDoCheck

This is fired each time anything that can trigger change detection has fired (e.g. click handlers, http requests, route changes, etc…). This lifecycle hook is mostly used for debug purposes;

demonstrating when ngDoCheck is triggered.

You can see that ngDoCheck is called on the child component when the parent component is being checked. Now suppose we implement onPush strategy for the B component. How does the flow change? Let’s see:

Checking A component:
  - update B input bindings
  - call NgDoCheck on the B component
  - update DOM interpolations for component A
 if (bindings changed) -> checking B component:
    - update C input bindings
    - call NgDoCheck on the C component
    - update DOM interpolations for component B

   Checking C component:
      - update DOM interpolations for component C
1
On

The reason is already described on angular life cycle documentation https://angular.io/guide/lifecycle-hooks#docheck

Normally Use this method to detect a change that Angular overlooked.

Most of these initial checks are triggered by Angular's first rendering of unrelated data elsewhere on the page. Mere mousing into another triggers a call. Relatively few calls reveal actual changes to pertinent data. Clearly our implementation must be very lightweight or the user experience suffers.

1
On

Angular Change Detection - How Does It Really Work?

... Angular always running change detection twice, the second time for detecting this type of cases. In production mode change detection is only run once