微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-Angular 2过滤器管道

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

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>

零件

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

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

我的商品具有visible属性,可以为true或false.

但是什么都没显示,我的烟斗有问题吗?

我认为我的管道正在运行,因为当我将管道代码更改为:

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

它将显示所有项目.

谢谢

解决方法:

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

添加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

每次修改(添加/删除)项目后,Angular都会使更改识别出来并重新执行管道.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐