You*_*suf 4 angular2-template angular
我有一个自定义管道来过滤数组。管道用于子组件内部,数据通过输入参数传递到子组件。当输入数据改变时,管道不会被调用。在子组件中使用 ChangeDetectionStrategy.OnPush 时,我需要做些什么不同的事情吗?
编辑
在下面的示例中,product-list-container 从 ngrx 商店获取产品。数据通过输入参数传递到产品列表组件。
在产品列表组件中,我有一个过滤器,用于根据某些条件过滤掉行。我看到的问题是,当输入值更改时,不会调用管道函数。Pipe 在组件加载时仅被调用一次。
@Component({
selector: 'product-list-container',
template: `
<app-product-list [productList]="productList$ | async"></app-product-list>
`
})
export default class ProductListContainer implements OnInit {
public productList$: Observable<Product[]>;
constructor(public store: Store<AppState>) {
}
ngOnInit() {
this.productList$ = this.store.select('productList');
}
}
@Component({
selector: 'app-product-list',
template: `
<div *ngFor="let product of productList | filterActiveProduct">
// More code here
</div>
`,
changeDetection: changeDetectionStrategy.onPush
})
export default class ProductList {
@Input() productList: Product[];
constructor() {
}
}
@Pipe({
name: 'fromNow'
})
export class filterActiveProduct {
transform(products: Product[], args: Array<any>): string {
return products.findAll(p => p.isActive);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢,
那是因为你的管道是Pure pipes。
仅当 Angular 检测到输入值的纯更改时,才会执行纯管道。纯粹的更改是对原始输入值(字符串、数字、布尔值、符号)的更改或更改的对象引用(日期、数组、函数、对象)。
Angular 忽略(复合)对象内的更改。如果我们更改输入月份、添加到输入数组或更新输入对象属性,它不会调用纯管道。
在你的情况下使用Impure pipes:
Angular 在每个组件更改检测周期期间执行不纯的管道。不纯的管道会被调用很多次,就像每次击键或鼠标移动一样频繁。
考虑到这一点,我们必须非常小心地使用不纯的管道。昂贵且长时间运行的管道可能会破坏用户体验。
过滤活性产品:
@Pipe({
name: 'filterActiveProduct',
pure: false
})
export class FilterActiveProduct {}
Run Code Online (Sandbox Code Playgroud)
产品列表:
@Component({
selector: 'app-product-list',
template: `
<div *ngFor="let product of productList | filterActiveProduct">
// More code here
</div>
`,
})
export default class ProductList {
@Input() productList: Product[];
constructor() {
}
}
Run Code Online (Sandbox Code Playgroud)
以下文档页面:https://angular.io/docs/ts/latest/guide/pipes.html
| 归档时间: |
|
| 查看次数: |
2964 次 |
| 最近记录: |