3

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

Catweazle
  • 105
  • 1
  • 8

3 Answers3

4

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

Nail Achmedzhanov
  • 1,264
  • 1
  • 9
  • 12
  • @Catweazle "this type of cases" refer to a cycle of detect changes **a notify b, and b notify a**. double detect changes happens only when development flag is active. if cycle is detected it will throw (has changed after it was checked Exception) – michelnem Dec 19 '21 at 12:51
0

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.

Chintan Kukadiya
  • 784
  • 5
  • 16
  • 1
    Thans for the answer, but it gaves me not a real reason why. I also read the documentation. Here I found a possible reason at the first answer of the following question: [link](https://stackoverflow.com/questions/45412199/angular-change-detection-runs-eight-times-instead-four/45412670#45412670) – Catweazle Jun 27 '19 at 09:27
0

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
Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39