在我的应用程序中,我想设置手动更改检测。为此,我将 ChangeDetectionStrategry 设置为 OnPush,每当组件中发生更改时,我都会使用 detectChanges 手动运行更改检测。
如果我在父组件上将 ChangeDetectionStrategy 设置为 OnPush,根据我的理解,即使我没有在子组件上将 ChangeDetectionStrategy 设置为 OnPush,它也只会在父组件上运行一次变更检测,在子组件上仅运行一次。如果父组件有任何变化,我会在父组件中运行 detectChanges() 。如果子组件有任何变化,我会在子组件中运行 detectChanges()。
请建议这是正确的方法吗?或者有什么更好的方法吗?
其次,有什么方法可以检查它是否按预期工作,并且没有对特定组件执行更改检测。
最佳答案
如果您想要“手动”更改检测,请使用 ChangeDetectorRef.detach()而不是 OnPush
。如果您有一个包含(大量)数据且变化非常频繁的组件,您可能想要这样做,因此您想要/需要控制更改检测运行的频率(即,何时更新 View ),以便用户界面保持响应(即,浏览器不会因过多的变化检测而陷入困境)。
上述用例很少见,您可能希望使用 OnPush
来限制更改检测在您的组件上运行的频率,而不是完全手动更改检测。 @Günter 已经在他的回答中涵盖了 OnPush
。
is there any way to check if its working as expect and no change detection is performed on a particular component
是的,实现 ngDoCheck()
并在其中放置一个 console.log()
。这个方法是called whenever change detection runs on your component/directive .
关于angular - 如何检查是否在组件上触发了变更检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39686397/