角 - 不纯管VS功能

问题描述 投票:2回答:2

我在Angular2阵列上实现滤波操作。纯管没有触发时数组中的元素的变化。因此,我必须使用任一不纯的管道或使用功能的过滤部件的内部等的下方。

*ngFor="let item of items | impureFilterPipe"

要么,

<!-- component.html -->
*ngFor="let item of filterFunction(items)"

// component.ts
sortFunction(items) { return items.sort(); }

据我所知,在模板结合的功能是在性能此事不好。不过,我看不到使用不纯的管道,而不是功能的任何差别。我想知道的是,有没有关于上述这两种技术途径之间的性能有什么区别?

angular data-binding angular-pipe angular-changedetection
2个回答
2
投票

正如在评论中指出,角队自己建议不要使用管道过滤或排序的集合。的解释是,这些管道将基本上在每次变更检测周期运行,使它们即使有小的藏品相当昂贵。

标准解决方案是让对何时执行排序操作,就像控制:

*ngFor="let item of filteredItems"

ngOnInit() {
  this.filteredItems = this.items.filter(/***/);
  ...
}

如果要按需运行它,你也可以换这个逻辑在其自身的功能。


1
投票

不建议使用不纯的管道。它会影响你的表现。即使源没有被改变,它就会调用,所以正确的方法是改变你的返回对象的引用。甚至更好,过滤逻辑移动到组件级。

// inside component
someMethod():void{
  this.items.push(newItem);
this.items = Object.clone(this.items);
}


@Pipe({
    name: 'showfilter'
})

export class ShowPipe {
    transform(value) {
        return value.filter(item => {
            return item.visible == true;
        });
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.