In Angular 2 when using ngFor how would I get the original index for an object within an array after it has been passed through a pipe?
For example if I have an arra
You can also use reduce
method to keep original index:
@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, []);
}
}
and then in html
{{item.index}} - {{item.value.id}}
Plunker Example
If i understood you correctly you want index of original list, in that case you can use that filtered object to find out origin index from original list.
<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>
and then define geIndex method in you component which can return Index from original list which is not been filtered.
getIndex(item: Item) {
return this.list.indexOf(this.list.filter((i, index) => item.id == i.id)[0])
}