How to know that ChangeDetection was executed on specific component?

324 Views Asked by At

I'm doing research on how ChangeDetection works in Angular.

One way of trigger ChangeDetection is to run method detectChanges():

constructor(cd: ChangeDetectorRef) { 
  setTimeout(_ => cd.detectChanges(), 3000)
}

It will execute change detection on the component but did not touch any component lifecycle hooks.

So if you try to do ngDoCheck or ngAfterViewChecked inside the same component:

  ngDoCheck() {
    console.log('ChangeDetection')
  }

  ngAfterViewChecked() {
    console.log('ChangeDetection')
  }

you will get nothing in the console.

Here you can play with the code - https://stackblitz.com/edit/ng-cd-check?file=src%2Fapp%2Fhello.component.ts

So my question is:

Is there a general way (that will work for all the cases) to define that ChangeDetection was executed on a specific component?
1

There are 1 best solutions below

0
On

I found a simple solution when inside a template I put a dummy function:

{{realDoCheck()}}

and as we know function will be always called when CD tries to rerender the template, so:

  realDoCheck() {
    console.log('CD triggered')
  }

here is a complete code example - https://stackblitz.com/edit/ng-cd-check-dyudp6?file=src%2Fapp%2Fhello.component.ts