angularangular-changedetection

Angular not calling the detectChanges() method on button click (change detection)


I have added a breakpoint in the angular source code on the detectChanges() method:

enter image description here

I noticed that when I click on the button from the component below, the breakpoint is not hit.

import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-some',
  standalone: true,
  imports: [],
  template: `
    <button (click)="onClick()">click me</button>
    <h3>{{ someValue }}</h3>  `,
  styleUrl: './some.component.scss'
})
export class SomeComponent implements DoCheck {

  ngDoCheck(): void {
    console.log('ngDoCheck');
  }

  someValue = 'initial value';

  onClick() {
    console.log('onClick');
    this.someValue = 'other';
  }

}

The tick method is indeed called though.

Can someone please explain in the context of angular change detection why the detectChanges() method is not called?


Solution

  • I think detectChanges is for manually trigger the change detection, like when you use OnPush detection, you have other methods to do similar like markForCheck. Angular might be using the latter for this or some internal method to trigger change detection.

    The console.log on the ngDoCheck event hook which fires when change detection runs. This is the best reference to check when change detection runs.

    Similar Question with stackblitz demo - Why property A is called when ngModel is used but not linked to that property A?