将 *ngFor 数据拆分为 2 列

问题描述 投票:0回答:2

我有这个html:

   <div class="w-full flex justify-center">
    <div *ngFor="let item of items" class="flex w-1/2">
        <span>{{item.label}}</span>
        <span>{{item.value}}</span>
    </div>
   </div>

这样UI中的html显示为:

LABEL 1 - VALUE 1 | LABEL 2 - VALUE 2
LABEL 3 - VALUE 3 | LABEL 4 - VALUE 4
LABEL 5 - VALUE 5 | LABEL 6 - VALUE 6

我需要显示这样的数据:

LABEL 1 - VALUE 1 | LABEL 4 - VALUE 4
LABEL 2 - VALUE 2 | LABEL 5 - VALUE 5
LABEL 3 - VALUE 3 | LABEL 6 - VALUE 6

我一直在努力寻找可行的解决方案,但运气不佳。你能建议工作解决方案吗?

angular flexbox ngfor
2个回答
0
投票

items
数组分成两半。

chunkedItems: any[][] = [];

let halfIndex = Math.floor(this.items.length / 2);
this.chunkedItems = [
  this.items.slice(0, halfIndex),
  this.items.slice(halfIndex, this.items.length),
  ];
}

并按如下方式构建弹性容器:

<div class="w-full flex flex-wrap justify-center">
  <ng-container *ngFor="let chunks of chunkedItems; let i = index">
    <div class="flex flex-col w-1/2">
      <div *ngFor="let item of chunks" class="flex">
        <span>{{item.label}}</span> -
        <span>{{item.value}}</span>
      </div>
    </div>
  </ng-container>
</div>

演示@StackBlitz


0
投票

试试这个代码

{{item.label}} - {{item.value}} {{item.label}} - {{item.value}}

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  items = [
    { label: 'LABEL 1', value: 'VALUE 1' },
    { label: 'LABEL 2', value: 'VALUE 2' },
    { label: 'LABEL 3', value: 'VALUE 3' },
    { label: 'LABEL 4', value: 'VALUE 4' },
    { label: 'LABEL 5', value: 'VALUE 5' },
    { label: 'LABEL 6', value: 'VALUE 6' }
  ];

  firstColumnItems() {
    return this.items.filter((item, index) => index % 3 === 0 || index % 3 === 1);
  }

  secondColumnItems() {
    return this.items.filter((item, index) => index % 3 === 2);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div class="w-full flex justify-center">
   
    <div class="w-1/2" *ngFor="let item of firstColumnItems()">
        <span>{{item.label}}</span> - <span>{{item.value}}</span>
    </div>
  
    <div class="w-1/2" *ngFor="let item of secondColumnItems()">
        <span>{{item.label}}</span> - <span>{{item.value}}</span>
    </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.