【问题标题】:Angular 2 - ngFor index after a pipeAngular 2 - 管道后的 ngFor 索引
【发布时间】: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


【解决方案1】:

您也可以使用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

【讨论】:

    【解决方案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])
    }
    

    【讨论】:

    • 这是我一开始的方法之一,但我认为保留原始索引的原因是不要再次计算索引以节省一些内存。如果我们有一个巨大的列表,再次查找索引将太昂贵。
    • @trungk18 另一种方法是使用索引映射一次列表,这样您就可以拥有列表中每个项目的索引,并且您根本不需要任何循环。
    • 是的,可能我们一开始就做地图,把索引保存在对象里面。
    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 2017-03-27
    • 2017-11-01
    • 2016-12-28
    • 2017-09-09
    • 2016-04-19
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多