【发布时间】:2017-03-13 10:42:59
【问题描述】:
在 Angular 2 中使用 ngFor 时,如何在数组中通过管道后获取对象的原始索引?
例如,如果我有一个对象数组,如下所示:
list = [{type:"A",id:111},{type:"A",id:222},{type:"B",id:333},{type:"A",id:444},{type:"B",id:555}];
并使用以下管道:
@Pipe({
name: 'appFilter',
pure: false
})
export class AppFilterPipe implements PipeTransform {
// Single Argument Filter
transform(values: any[], arg1: any, arg2: any): any {
return values.filter(value => value[arg1] === arg2);
}
}
我创建一个ngFor如下:
<div *ngFor= "let item of list|AppFilter:'type':'B'|let index=index;trackBy:trackByIndex;">
{{index}} - {{item.id}}
<input [(ngModel)]="list[index]" placeholder="item">
</div>
这里的问题是 ngFor 返回的索引是基于 AppFilter 返回的新数组,即索引 0 和 1。这将导致输入字段引用错误的索引,即它将显示类型 A 对象,因为它对应在原始列表中索引 0,1。要获得 B 型,我真的需要索引 2,4。
感谢解决此问题。我在组件中的 trackByIndex 目前看起来像:
trackByIndex(index: number, obj: any): any {
return index;
}
【问题讨论】:
-
我认为最好在分配给
list之前进行过滤。
标签: angular