1

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.

1 Answer 1

0

Since v18, markForCheck schedules change detection.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the info. Would you mind sharing the source? I checked release note and source code but haven't found anything.
The change spans several commits and is not obvious in the change log. This commit is probably the closest to what you are looking for. github.com/atscott/angular/commit/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.