在Angular 2中使用ng时,如何在数组通过管道后获取对象内的原始索引?
例如,如果我有一个对象数组,如下所示:
list = [{type:"A",id:111},{type:"A",id:222},{type:"B",id:333},{type:"A",id:444},{type:"B",id:555}];
Run Code Online (Sandbox Code Playgroud)
并使用以下管道:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
我创建一个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>
Run Code Online (Sandbox Code Playgroud)
这里的问题是ngFor返回的索引是基于AppFilter返回的索引为0和1的新数组.这将导致输入字段引用错误的索引,即它将显示类型A对象,因为它对应于索引0 ,1在原始列表中.要获得Type BI,确实需要索引2,4.
欣赏这方面的工作.我的组件中的trackByIndex目前看起来像:
trackByIndex(index: number, obj: any): any {
return index;
}
Run Code Online (Sandbox Code Playgroud)
yur*_*zui 10
您还可以使用reduce
方法来保留原始索引:
@Pipe({
name: 'appFilter',
pure: false
})
export class AppFilterPipe implements PipeTransform {
transform(values: any[], arg1: any, arg2: any): any {
return values.reduce((acc, value, index) =>
value[arg1] === arg2 ? [...acc, { index, value }] : acc, []);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在HTML中
{{item.index}} - {{item.value.id}}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5369 次 |
最近记录: |