Angular2 OnPush 变化检测和 ngFor

Angular2 OnPush change detection and ngFor

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

这很有帮助,但仍然有少数情况会减慢速度,我可以看出这是由于不必要地为每个 children 执行了更改检测。

一个例子是 child 组件中有一个点击事件 - 即使没有输入被改变并且它只是触发了一个动画,出于某种原因正在为 [=42= 执行变化检测] 组件以及每个 child 组件的结果(即使 ngFor 背后的模型根本没有改变并且它是 OnPush 策略......)。我原以为这种 "isolated" 事件应该只触发那个特定 child 组件的变化检测而不是向上传播(我实际上已经尝试过 event.stopPropagation()event.preventDefault() 没有成功)。

所以我想知道两件事:

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

2) 在每个 child 组件(来自 ng2translate)中大量使用 "translate" 管道会减慢 application/change 检测速度吗?

下面的示例 plunkr 显示问题所在。基本上,如果我点击 ngFor 列表中的任何项目,它会针对每个 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) 管道(如果它们是纯管道,这是默认设置)仅在管道值或参数更改时调用,因此没有性能劣势。