角度-不纯管道与功能 [英] Angular - Impure pipe vs function
问题描述
我正在Angular2中对数组实施过滤操作。当数组中的元素更改时,纯管道不会触发。因此,我必须使用不纯管道或使用组件内部的函数进行过滤,如下所示。
I am implementing a filtering operation on an array in Angular2. A pure pipe is not triggering when an element change in the array. Thus, I have to use either an impure pipe or make the filtering with a function inside of the component like below.
*ngFor="let item of items | impureFilterPipe"
或者,
<!-- component.html -->
*ngFor="let item of filterFunction(items)"
// component.ts
sortFunction(items) { return items.sort(); }
据我所知,将模板中的函数绑定在性能上是不好的。但是,我看不到使用不纯管道而不是函数的区别。我想知道的是,以上两种方法之间的性能是否存在差异?
As I know, binding a function in the template is bad in the matter of performance. However, I can't see any difference of using an impure pipe instead of a function. What I am wondering is that are there any difference about the performance between these two approachs above?
推荐答案
如评论中所指出的,Angular团队自己建议不要使用管道对集合进行过滤或排序。解释是这些管道实际上将在每个变更检测周期运行,因此即使收集的资源很少,它们也相当昂贵。
As pointed out in the comments, the Angular team themselves advise against using pipes to filter or sort a collection. The explanation is that those pipes would be run essentially at every change detection cycle, making them quite expensive even with small collections.
标准解决方案是控制何时进行进行排序操作,例如:
The standard solution is to have control over when to do the sorting operation, like:
*ngFor="let item of filteredItems"
ngOnInit() {
this.filteredItems = this.items.filter(/***/);
...
}
您也可以自己包装逻辑函数,如果您想按需运行它。
You could also wrap that logic in its own function if you want to run it on demand.
这篇关于角度-不纯管道与功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!