试图写一个自定义的管道隐藏一些项目。
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;
}
}
它会显示所有项目。
谢谢
我敢肯定,这是因为你有[]
为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
被修改后(添加/移除)时,使角识别更改和重新执行管。
@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
}
}