Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Impure pipe vs function

Tags:

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?

like image 519
Bünyamin Sarıgül Avatar asked Jun 18 '18 08:06

Bünyamin Sarıgül


2 Answers

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.

like image 179
bugs Avatar answered Oct 11 '22 14:10

bugs


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

like image 43
Ritu Gupta Avatar answered Oct 11 '22 12:10

Ritu Gupta