gpt4 book ai didi

performance - Angular2 OnPush 变化检测和 ngFor

转载 作者:太空狗 更新时间:2023-10-29 18:25:49 25 4
gpt4 key购买 nike

我有一个使用 ngFor 显示子组件列表的父组件。我注意到随着 child 数量的增加,性能变得非常糟糕,所以我将两者都更改为 OnPush 更改检测策略。

这很有帮助,但仍然有一些情况会变慢,我可以看出这是因为对每个 child 不必要地执行了变化检测。

一个例子是当子组件内部有一个点击事件时——即使没有输入被改变并且它只是触发了一个动画,出于某种原因,变化检测正在为父组件执行,结果是为每个子组件同样(尽管 ngFor 背后的模型根本没有改变,它是一个 OnPush 策略......)。我本以为这种“隔离”事件应该只触发那个特定子组件的变化检测而不是向上传播(我实际上已经尝试过 event.stopPropagation()event.preventDefault () 没有成功)。

所以我想知道两件事:

1) 是否有任何方法可以更好地控制实际运行的事件更改检测以及它是否也触发父组件更改检测?

2) 在每个子组件(来自 ng2translate)中大量使用“翻译”管道会减慢应用程序/更改检测的速度吗?

下面的示例 plunkr 显示问题所在。基本上,如果我点击 ngFor 列表中的任何项目,它会为每个 child 启动变化检测,而不仅仅是受影响的 child ,我想知道是否有任何方法可以抑制它。

https://plnkr.co/edit/mD8HCbwq0cEwPt7itpCf

最佳答案

1) 您可以使用ChangeDetectorRef.detach()

https://angular.io/docs/js/latest/api/core/index/ChangeDetectorRef-class.html#!#detach-anchor

Detaches the change detector from the change detector tree.

The detached change detector will not be checked until it is reattached.

This can also be used in combination with ChangeDetectorRef to implement local change detection checks.

2) 管道(如果它们是纯管道,这是默认设置)仅在管道值或参数更改时调用,因此没有性能劣势。

关于performance - Angular2 OnPush 变化检测和 ngFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42067346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com