I couldn't really understand what is causing change detection to run in the below code. I understand that markForCheck doesn't do it but something must do it because the view is updated if you play it in https://angular.dev/playground.
import {bootstrapApplication} from '@angular/platform-browser';
import { Component, NgZone, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>Time: {{ currentTime }}</p>
`,
changeDetection: ChangeDetectionStrategy.OnPush // Use OnPush for better performance
})
export class IntervalExampleComponent implements OnInit, OnDestroy {
currentTime!: Date;
intervalId!: any;
constructor(private ngZone: NgZone, private changeDetectorRef: ChangeDetectorRef) {}
ngOnInit() {
this.ngZone.runOutsideAngular(() => {
this.intervalId = setInterval(() => {
this.currentTime = new Date();
this.changeDetectorRef.markForCheck();
}, 1000);
});
}
ngOnDestroy() {
clearInterval(this.intervalId);
}
}
bootstrapApplication(IntervalExampleComponent);
I expect to see no view update since setInterval is run outside of angular zone and markForCheck doesn't trigger change detection.