balteo
balteo

Reputation: 24679

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?

Upvotes: 1

Views: 41

Answers (2)

hajrovica
hajrovica

Reputation: 224

As i can recall detectChanges should be trigged on: DOM events, Asynchronous tasks and Component lifecycle events, accent here is on "it should" there are cases (in my experiece at least) where angular does not trigger change detection automatically (when change is runnning outside of Angular zone) in that cases you should trigger change manually, for example using ChangeDetectorRef:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef) {}

someMethod() {
  // Code that doesn't trigger automatic change detection
  this.value = 'Updated manually';
  
  // Manually trigger change detection
  this.cdr.detectChanges();
}

but for most cases, for me, more direct way is to do what ever you need after you change value. So for given example if You are changing something onClick() and expecting some reaction to change caused by that method call another method from within onClick() which will do something yo expect with given data?

Upvotes: 0

Naren Murali
Naren Murali

Reputation: 56600

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?

Upvotes: 1

Related Questions