Angular - Impure pipe vs function

2019-07-20 11:12发布

问题:

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"

Or,

<!-- 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?

回答1:

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.



回答2:

It is not recommended to use impure pipe. It will impact your performance. It will be called even when the source has not been changed, so the correct alternative is to change the reference of your returning object. Or even better, to move the filtering logic to the component level.

// 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;
        });
    }
}