【问题标题】:How to split array by four items in ngFor?如何在 ngFor 中将数组拆分为四个项目?
【发布时间】:2019-05-20 21:26:32
【问题描述】:

如何在 ngFor 中将数组拆分为四项?

如何在此处显示 4 个项目而不是一个?

   <div *ngFor="let item of items$ | async">
     // How can I show here 4 projects instead of one?
     {{item}}
    </div>

【问题讨论】:

  • 不清楚您的要求。 How can I show here 4 projects instead of one????
  • 至少向我们展示你的 JSON
  • 我认为那里有很多适合您的答案,但需要有关您的架构和您想要实现的目标的更多信息。 @stingingdafunk 有最优雅的答案,但可能值得查看我的答案和其他答案并了解它们的工作原理,以便您对 *ngFor、管道和组件中的数据操作有更广泛的了解。

标签: arrays angular typescript ngfor


【解决方案1】:

将您在组件中使用的数组重组为一个数组数组,每个数组包含 4 个元素。

let items = [ [1, 2, 3, 4], [5,6,7,8] ];

这是一个如何使用循环进行重组的示例:

const items = [1, 2, 3, 4, 5, 6, 7, 8];
const parentArray = [];
let childArray = [];
items.forEach(item => {
     childArray.push(item);
     if(childArray.length === 4){
          parentArray.push(childArray);
          childArray = [];
     }
});

然后在模板的第一个内嵌套另一个“ngFor”:

<div *ngFor=“let item of parentArray”>
    <div *ngFor=“let subItem of item>
        {{ subItem }}
    </div>
</div>

这不是一个非常优雅的解决方案,但这正是您所要求的。

【讨论】:

    【解决方案2】:

    你可以试试这个(使用slice pipe): TS:

    export class AppComponent  {
      private itemsInRow = 4;
      // dummy array of 14 integers
      private arr = Array.from(Array(14).keys());
    
      itemInRowRange = Array.from(Array(this.itemsInRow).keys());
      items = of(this.arr);
    }
    

    HTML:

    <div class="outer" *ngFor="let i of itemInRowRange">
      <div class="box" *ngFor="let item of items | async | slice: i*4 : i*4 + 4">
        {{item}}
      </div>
    </div>
    

    STACKBLITZ

    【讨论】:

      【解决方案3】:

      组件:

      public items: string[] = [
          "one",
          "twho",
          "three",
          "four",
          "five",
          "six",
          "seven",
          "eight",
          "nine",
          "ten"
      

      ]

      模板:

      <div *ngFor="let item of items; let i = index">
        <ng-container *ngIf="i % 4 == 0 || i == 0">
          {{items[i]}}
          {{items[i+1]}}
          {{items[i+2]}}
          {{items[i+3]}}
        </ng-container>
      </div>
      

      一般的想法是检查你正在迭代的数组中当前元素的索引是否是4的倍数

      【讨论】:

        猜你喜欢
        • 2017-03-03
        • 2012-03-29
        • 2014-06-08
        • 2020-01-17
        • 1970-01-01
        • 2013-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多