gpt4 book ai didi

Angular 2 - 管道后的 ngFor 索引

转载 作者:太空狗 更新时间:2023-10-29 17:13:35 25 4
gpt4 key购买 nike

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

最佳答案

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

关于Angular 2 - 管道后的 ngFor 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40340661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com