A gentle introduction into change detection in Angular

Here you mention that adding the interval which changes the time inside zone will cause a lot of change detection calls ( after every call back of setInterval macrotask?).
so we run it outside the zone to allow it to be detected in change detection caused by some other async change.
I thought of this in addition to running it outside zone -

constructor(zone: NgZone, cd: ChangeDetectorRef) {
this._time = Date.now();
zone.runOutsideAngular(() => {
setInterval(() => {
cd.reattach();
this._time = Date.now();
cd.detectChanges();
cd.detach();
}, 1000);
});
}

According to my limited knowledge on this topic -

  1. should this cause the local change detection. and will ignore this during other change detection cycles (caused by other component’s change detection)
  2. I think reattach/detach is also not required but would like to know your guidance on this.
  3. Will the code I added above will provide more optimization as I think it will?

A link to ’ These 5 articles will make you an Angular Change Detection expert’ is broken

@oblogera, thanks, fixed!

yes, because you use cd.detectChanges()

it’s not required if you want to run it manually

more optimization than what?

@m.koretskyi more optimization than what?

Than optimization provided by runOutSideAngular method.
So,

  1. Because we are calling it outside Angular we will avoid unnecessary change detection cycles caused by this async setTimeout event - as this will cause change detection cycle every second and hence it will also check the whole hierarchy of components which is overload.
  2. Because we are updating the ui of this component using local change detection, other change detection cycles can simply ignore this particular component if we use detach() after we finish local change detection? Because we are sure when exactly we want to update UI and only then we causes change detection locally.