尝试编写自定义管道以隐藏某些项目。
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;
}
}
它会显示所有项目。
由于
答案 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
}
}