首页 文章

角2过滤管

提问于
浏览
3

尝试编写自定义管道来隐藏一些项目 .

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

我的项目具有可见属性,可以是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;
    }
}

它会显示所有项目 .

谢谢

2 回答

  • 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
    

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

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

相关问题