我有一个没有逻辑的简单测试组件。我渲染这个组件。为什么 DoCheck 钩子被调用了两次?
到目前为止,我了解,每次更改检测都会调用 DoCheck。但是没有变化。我只是渲染组件并且 DoCheck 已经被调用了两次。还有 ngAfterContentChecked 和 ngAfterViewChecked。
我有一个没有逻辑的简单测试组件。我渲染这个组件。为什么 DoCheck 钩子被调用了两次?
到目前为止,我了解,每次更改检测都会调用 DoCheck。但是没有变化。我只是渲染组件并且 DoCheck 已经被调用了两次。还有 ngAfterContentChecked 和 ngAfterViewChecked。
... Angular 总是运行两次变更检测,第二次检测这种情况。在生产模式下,变更检测只运行一次
角度生命周期文档https://angular.io/guide/lifecycle-hooks#docheck已经描述了原因
一般Use this method to detect a change that Angular overlooked.
大多数这些初始检查都是由 Angular 在页面其他地方首次渲染无关数据触发的。仅仅将鼠标移入另一个就会触发呼叫。相对较少的调用揭示了相关数据的实际变化。显然,我们的实现必须非常轻量级,否则用户体验会受到影响。
ngDoCheck
每次触发更改检测的任何事情(例如点击处理程序、http 请求、路由更改等)都会触发此事件。这个生命周期钩子主要用于调试目的;
演示何时触发 ngDoCheck。
您可以看到ngDoCheck
在检查父组件时在子组件上调用了它。现在假设我们为 B 组件实现 onPush 策略。流量如何变化?让我们来看看:
Checking A component:
- update B input bindings
- call NgDoCheck on the B component
- update DOM interpolations for component A
if (bindings changed) -> checking B component:
- update C input bindings
- call NgDoCheck on the C component
- update DOM interpolations for component B
Checking C component:
- update DOM interpolations for component C