Angular 2 - ngFor管道后的索引

时间:2016-10-31 10:48:12

标签: angular

在Angular 2中使用ng时,如何在数组通过管道后获取对象的原始索引?

例如,如果我有一个对象数组,如下所示:

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;
  }

2 个答案:

答案 0 :(得分: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, []);
  }
}

然后在html中

{{item.index}} - {{item.value.id}}

<强> Plunker Example

答案 1 :(得分:2)

如果我理解正确你想要原始列表的索引,那么你可以使用该过滤的对象从原始列表中找出原始索引。

<div *ngFor= "let item of list|appFilter:'type':'B'|let index=index;trackBy:trackByIndex;">
 {{getIndex(iteml)}} - {{item.id}}
  <input [(ngModel)]="list[getIndex(item)].id" placeholder="item">
</div>

然后在你的组件中定义geIndex方法,该方法可以从原始列表中返回未被过滤的索引。

getIndex(item: Item) {
    return this.list.indexOf(this.list.filter((i, index) => item.id == i.id)[0])
}
相关问题