Angular 2-管道后的ngFor索引 [英] Angular 2 - ngFor index after a pipe

查看:76
本文介绍了Angular 2-管道后的ngFor索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 array of objects as follows:

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,如下所示:

I create an ngFor as follows:

<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.要获得Type B,我真的需要索引2,4.

The issue here is the index returned by the ngFor is based on new array returned by AppFilter that is index 0 and 1. This will cause the input field to reference the wrong index ie it will show the type A objects as it corresponds to index 0,1 in the original list. To get Type B I really need the index 2,4.

对此很感激.另外,我在组件中的trackByIndex当前看起来像:

Appreciate a work around to this. Also my trackByIndex in the component currently looks like:

trackByIndex(index: number, obj: any): any {
    return index;
  }

推荐答案

您还可以使用reduce方法保留原始索引:

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, []);
  }
}

然后是html

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

柱塞示例

Plunker Example

这篇关于Angular 2-管道后的ngFor索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆