Angular 2 Filter Pipe

时间秒杀一切 提交于 2019-12-01 21:51:29

问题


Trying to write a custom pipe to hide some items.

import { Pipe } from '@angular/core';

// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
    name: 'showfilter'
})

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

HTML

<flights *ngFor="let item of items | showfilter">
</flights>

COMPONENT

import { ShowPipe } from '../pipes/show.pipe';

@Component({
    selector: 'results',
    templateUrl: 'app/templates/results.html',
    pipes: [PaginatePipe, ShowPipe]
})

My item has the property of visible, which can be true or false.

However nothing showing, is there something wrong with my pipe?

I think my pipe is working because when I change the pipe code to:

import { Pipe } from '@angular/core';

// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
    name: 'showfilter'
})

export class ShowPipe {
    transform(value) {
        return value;
    }
}

It will show all items.

Thanks


回答1:


I'm pretty sure this is because you have an initial value of [] for items. When you then later add items to items, the pipe is not reexecuted.

Adding pure: false should fix it:

@Pipe({
    name: 'showfilter',
    pure: false
})
export class ShowPipe {
    transform(value) {
        return value.filter(item => {
            return item.visible == true;
        });
    }
}

pure: false has a big performance impact. Such a pipe is called every time change detection runs, which is quite often.

A way to make a pure pipe being called is to actually change the input value.

If you do

this.items = this.items.slice(); // create a copy of the array

every time after items was modified (added/removed) makes Angular recognize the change and re-execute the pipe.




回答2:


  • It is not recommended to use impure pipe. I will impact your performance.
  • It will be called even source has not been changed.
  • So the correct alternative to be is change the reference of your returning object.

@Pipe({
    name: 'showfilter'
})

export class ShowPipe {
    transform(value) {
        value = value.filter(item => {
            return item.visible == true;
        });
     const anotherObject = Object.assign({}, value) // or else can do cloning.
     return anotherObject 
    }
}


来源:https://stackoverflow.com/questions/37827925/angular-2-filter-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!