代码之家  ›  专栏  ›  技术社区  ›  Trung Bún

角度6:存储要在*ngFor中使用的值

  •  0
  • Trung Bún  · 技术社区  · 6 年前

    在下面代码的循环体中:


    <ul>
       <li *ngFor="let article of articles; index as i">
           <a>{{ articles[i].title }} -- {{i}}</a>
           <p>{{ articles[i].body }}</p>
           <!-- i++ -->  
           <p>{{ i }}</p>
       </li>
    </ul>
    

    i++ 在该位置,然后打印出 i

    那么, 的值将用新值更新,并在下一个循环中使用。我想一次循环两个元素,而不是一个。

    就像我们在Java中可以做的那样:


    for (int i = 0; i < 10; i++) {
        System.out.println(i);
        i++;
        System.out.println(i);
    }
    

    第一回路:

    0

    第二回路:

    2

    以此类推。。


    我找到了解决方案,在这个链接中: Looping through list two at a time using *ngFor

    2 回复  |  直到 6 年前
        1
  •  1
  •   noitse    6 年前

    如果问题仍然相关,对于那些寻求答案的人,我建议你参考以下帖子: Looping through list two at a time using *ngFor

    这篇文章不是我写的,但它展示了一个使用管道的简单解决方案。

        2
  •  1
  •   Kaleab    6 年前

    使用此函数可将数据转换为要访问的结构类型。

    someData = [1,2,3,4,5,6];
    
    transformData(data) {
        let temp = []
        for(let i = 0; i < data.length; i++) {
          let temp2 = [];
          temp2.push(this.data[i]);
          i++;
          temp2.push(this.data[i])
          temp.push(temp2);
        }
        return temp;
      }
    

    然后像这样在html中访问它

    <p *ngFor="let data of transformData(someData)">
    {{data[0]}}, {{data[1]}}
    </p>
    
    推荐文章