angular - 如何检查是否在组件上触发了变更检测

标签 angular angular2-template angular2-directives angular2-changedetection

在我的应用程序中,我想设置手动更改检测。为此,我将 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/

相关文章:

angular - NGINX 和 Angular 2

angular - 错误: 'observableFactory is not a function' when using 'defer'

javascript - 在 Angular 2 中使用 CKEditor 的自定义配置文件

angular - 从 Angular 2 组件中访问 `selector`

Angular 异常 : Can't bind to 'ngForIn' since it isn't a known native property

php - 如何使用 Http.post (Angular 2) 发布 json 对象(php 服务器端)

javascript - 在 Angular 中使用 Javascript 库

angular - 模型驱动/ react 形式 : Auto mapping from Model to FormGroup ?

angular - 输入更改时不调用子组件内的管道

typescript - 子组件事件广播给父组件