本文介绍了角2过滤管的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

COMPONENT

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

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

我的项目具有可见属性,可以是true或false。

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

它会显示所有项目。

谢谢

推荐答案

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

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.

添加 pure:false 应该修复它:

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

pure:false 对性能有很大影响。每次更改检测运行时都会调用这样的管道,这很常见。

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.

如果你这样做

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

c $ c>被修改(添加/删除)使Angular识别出更改并重新执行管道。

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

这篇关于角2过滤管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:23