5

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

CruelEngine
  • 2,701
  • 4
  • 23
  • 44
  • Answer : https://blog.angularindepth.com/if-you-think-ngdocheck-means-your-component-is-being-checked-read-this-article-36ce63a3f3e5 – SeleM Nov 13 '18 at 13:00
  • @selemmn the article doesn't not mention anything about ``changeDetectorRef.detach()`` and how ``ngDoCheck()`` behaves or change detection behaves due to this :( – CruelEngine Nov 13 '18 at 14:00

1 Answers1

0

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

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • the official docs says that ngDoCheck() is called after every change detection cycle . But here I've detached the ``changeDetector`` , so change detection shouldn't be called until it is reattached , so ``ngDoCheck()`` shouldn't be called right ? or am i missing something here ? – CruelEngine Nov 13 '18 at 13:55
  • @CruelEngine your interpretation is wrong. A change detection cycle is a `tick()` from `ApplicationRef`. This is always called, regardless of your components change detector settings. `NgDoCheck` is not a part of the components changeDetector, but is a custom change detection implementation. This will always be called – Poul Kruijt Nov 13 '18 at 14:03
  • i created another example to understand the working of ``ngDoCheck()`` in the similar way . ``ngDoCheck()`` is being called only after 5 seconds when ``ref.reattach()`` is called . Stackblitz link : https://stackblitz.com/edit/angular-r2zlev – CruelEngine Nov 13 '18 at 14:51
  • in your example it's called at the same time. Not because of the reattach, but because the setInterval got triggered. This will trigger a `tick` throughout the application – Poul Kruijt Nov 13 '18 at 14:59