Angular ChangeDetectionStrategy and disabling zone.js

5.5k views Asked by At

I'm currently working on very lightweight Angular Elements with Ivy (v10.1.2).

When I don't import zone.js in my polyfills.ts and "disable" it in my main.ts as follows:

platformBrowserDynamic()
  .bootstrapModule(AppModule, { ngZone: 'noop' })
  .catch(err => console.error(err));

then is it still relevant what kind of ChangeDetectionStrategy I set on my component?

So, if I trigger it manually by marking the component as dirty (ɵmarkDirty as markDirty) and having the default ChangeDetectionStrategy, would the Noop-ChangeDetector traverse the whole tree? And if I would set it to changeDetection: ChangeDetectionStrategy.OnPush would it just check the component at hand?

1

There are 1 answers

0
fox On BEST ANSWER

I actually asked the same question in a great medium article and got the following response (short version):

When we disable Zone.js, we still have the Change Detector, but nobody will run the change detection for us. We have to mark the Component as dirty ourselves.

That actually answered my question, as I thought that we don't have a Change Detector, because we would be Change Detector (because we mark the Component dirty ourselves).

It goes on:

As for the ChangeDetectionStrategy it is slightly useful, because all of the objects that I am using in the template are immutable. Let me explain why this matters. When the Change Detection runs it will check if any object that I am using in the template changed or not. If I was using Default Change Detection Strategy, it would check any object with the deep equality check and it would go down the Component Tree into the children and do the same equality check. In my case, OnPush will do the referential equality check and that’s enough, because all of the objects that I am using are immutable and besides that I only have one component without any child components.

In summary, I disabled Zone.js to reduce bundle size, because I am manually triggering the Change Detection whenever it’s time and I enabled OnPush, because all of my objects are immutable and I am improving performance of the actual Change Detection by reducing number of checks.

So my takeaway and in conclusion:

When disabling zone.js (we still have a ChangeDetector) and by using the default strategy (instead of the OnPush) and triggering the change detection manually (with markDirty), the ChangeDetector will check the whole tree (assuming every component has default change detection strategy). But when using OnPush, the ChangeDetector will only check the component at hand.