角2过滤管

时间:2016-06-15 06:46:19

标签: javascript angular angular-pipe

尝试编写自定义管道以隐藏某些项目。

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

我的项目具有可见属性,可以是真或假。

然而没有任何显示,我的烟斗有问题吗?

我认为我的管道工作正常,因为我将管道代码更改为:

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

它会显示所有项目。

由于

2 个答案:

答案 0 :(得分:2)

我很确定这是因为[]的初始值为items。然后,当您稍后将项目添加到items时,不会重新执行管道。

添加pure: false应修复它:

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

pure: false会对性能产生重大影响。每次更改检测运行时都会调用这样的管道,这种情况经常发生。

调用纯管道的方法是实际更改输入值。

如果你这样做

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

每次修改items(添加/删除)后,Angular都会识别更改并重新执行管道。

答案 1 :(得分:1)

  • 不建议使用不纯的管道。我会影响你的表现。
  • 即使源未更改,也将被称为
  • 所以正确的选择是更改返回对象的引用。

@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 
    }
}
相关问题