why is ngDoCheck() being called when i have called detach() from ChangeDetectorRef?

Viewed 439

I was going through some articles on change detection and i was trying to enable or disable change detection using the changeDetectorRef.detach() and changeDetectorRef.reattach() .

I also hooked the component to the ngDoCheck() only to find ngDoCheck() being called even after detach() . What am i doing wrong ? Can someone explain why ngDocheck() is called ? I have even the ChangeDetectionStartegy set to OnPush too . This is the article i was going through to understand change detection

I have also created an example for this : https://stackblitz.com/edit/angular-4ytdbs

1 Answers

That's because detach() detaches the component from it's own ChangeDetector, making it not check the template/input/host bindings. This is a different thing than ngDoCheck is doing. This is used to implement a sort of custom change detection, for changes that you know will happen, but angular cannot anticipate on. It's called for any cycle anywhere in the application.

I suppose the only way to not have your code run inside your ngDoCheck is to set a flag when detaching:

ngDoCheck(): void {
  if (attached) {
    // ...
  }
}

But I'm sure you have figured that one out as well :)

The link provided by @selemmn really gives a good insight

Related