Angular 在单击按钮时不调用 detectorChanges 方法

问题描述 投票:0回答:1

我在

detectChanges()
方法的 Angular 源代码中添加了一个断点:

enter image description here

我注意到,当我单击下面组件中的按钮时,没有命中断点。

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';
  }

}

tick 方法确实被调用了。

有人可以在角度变化检测的背景下解释为什么不调用

detectChanges()
方法吗?

angular angular-changedetection
1个回答
0
投票

我认为

detectChanges
用于手动触发更改检测,您还有其他方法可以执行类似的操作,例如
markForCheck
。 Angular 可能会使用后者来触发更改检测或某些内部方法。

console.log
事件挂钩上的
ngDoCheck
在运行更改检测时触发。这是检查何时运行更改检测的最佳参考。

stackblitz demo 的类似问题 - 为什么当使用 ngModel 但未链接到该属性 A 时会调用属性 A?

© www.soinside.com 2019 - 2024. All rights reserved.