在嵌套的* ngFor中生成累积索引 [英] Generate the cumulative index within a nested *ngFor

查看:85
本文介绍了在嵌套的* ngFor中生成累积索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要迭代的对象的嵌套列表,每个对象内部都有一个数组.

I have a nested list of objects which I am iterating over, each object has an array inside.

arr: any[] = [
    { 'title': 'fruits', res: ['apple', 'pear'] }, 
    { 'title': 'numbers', res: [3, 5, 7, 11] },
    { 'title': 'letters', res: ['a', 'b'] }];
];` 

我希望遍历每个嵌套数组res并输出累积索引,以使上述输出等于:

I wish to iterate over each nested array res and output the cumulative index so that the output of the above equals this:

fruits
0 - apple
1 - pear

numbers
2 - 3
3 - 5
4 - 7
5 - 11

letters
6 - a
7 - b

Angular公开了局部变量index,但是有一种方法可以定义其他局部变量并随着我们的进行递增.如下所示(我知道这不会渲染)

Angular exposes the local variable index, but is there a way to define other local variables and increment them as we go along. Something like the below (I know this doesn't render)

<div *ngFor="let list of comboList; let i = index; let count = 0">
    <h1>{{ list.title}}</h1>
    <div *ngFor="let item of list.res; let j = index; count ++">
        {{ count }} - {{ item }}
    </div>
</div>

到目前为止,我唯一可行的选择是每次我要显示一个项目时都会调用的函数,这不是很有效.

So far my only working option is a function which gets called each time I want to display an item, which isn't very efficient.

getCumIndex(arr: any[], x: number, y: number){
    let count: number = 0;
    for (let i = 0; i < arr.length; i++){
        if (x == i){
            return count + y;
        } else {
            count += arr[i].res.length;
        }
    }
}

推荐答案

这是油罐车使用自定义管道和帮助程序类的解决方案

Here is the plunker for solution with custom pipe and helper class

<div *ngFor="let counter of [comboList | counterPipe]">
  {{ counter.reset() }}
  <div *ngFor="let list of comboList">
    <h1>{{ list.title }}</h1>
    <div *ngFor="let item of list.res">
      {{ counter.inc() }} - {{ item }}
    </div>
  </div>
</div>

这篇关于在嵌套的* ngFor中生成累积索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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