角2滤水管

问题描述 投票:3回答: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]
})

我的项目有可见的财产,可以是真或假。

但是没有什么表现,是有什么错我管?

我想我管工作,因为当我管的代码更改为:

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

它会显示所有项目。

谢谢

javascript angular angular-pipe
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

items被修改后(添加/移除)时,使角识别更改和重新执行管。


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 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.