我在
detectChanges()
方法的 Angular 源代码中添加了一个断点:
我注意到,当我单击下面组件中的按钮时,没有命中断点。
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()
方法吗?
我认为
detectChanges
用于手动触发更改检测,您还有其他方法可以执行类似的操作,例如markForCheck
。 Angular 可能会使用后者来触发更改检测或某些内部方法。
console.log
事件挂钩上的 ngDoCheck
在运行更改检测时触发。这是检查何时运行更改检测的最佳参考。