How to nest html when looping through array using

2019-08-26 05:17发布

I'm trying to output html in the following format for an array

weekDaysHeaderArr whose length is 42 = 6 x 7.

In other words I want to nest every 7 column div elements in a row div (6 total) like so.

<div class="row">
    <div class="col-md-auto"> <-- **repeated 7 times**
    </div>
</div>
<div class="row">
    <div class="col-md-auto"> <-- **repeated 7 times**
    </div>
</div>
<div class="row">
    <div class="col-md-auto"> <-- **repeated 7 times**
    </div>
</div>
<div class="row">
    <div class="col-md-auto"> <-- **repeated 7 times**
    </div>
</div>
<div class="row">
    <div class="col-md-auto"> <-- **repeated 7 times**
    </div>
</div>
<div class="row">
    <div class="col-md-auto"> <-- **repeated 7 times**
    </div>
</div>

I can use ngFor to obviously produce the same html element (div class="col-md-auto">) 42 times but how do I nest every 7 elements inside a <div class="row"> ?

I've not used ng-template and ng-container before and I can't get my head around the documentation, can these be used to do this? As far as I can tell these are designed for switching between html elements rather than nesting.

3条回答
你好瞎i
2楼-- · 2019-08-26 05:38

Create a matrix from your array

private weekDaysHeaderArr = [ /*Your elements here*/ ]
private groupSize: number = 7;
get matrix(){ 
  return this.weekDaysHeaderArr.map((item, index, arr)=>{
    return index % this.groupSize === 0 ? arr.slice(index, index + this.groupSize) : null; 
  })
  .filter((item) => { return item; });
}

Then use it inside your template like this

<div class="row" *ngFor="let week of matrix">
    <div class="col-md-auto" *ngFor="let day of week">
    </div>
</div>

查看更多
Lonely孤独者°
3楼-- · 2019-08-26 05:39

You can do something like this....

<div class="row" *ngFor="let week of [0,1,2,3,4,5]">
    <div class="col-md-auto" *ngFor="let day of [0,1,2,3,4,5,6]">
    </div>
</div>

then, to get the index from weekDaysHeaderArr you can do....

 weekDaysHeaderArr[week * 7 + day];
查看更多
成全新的幸福
4楼-- · 2019-08-26 05:55

Nesting for-loops in angular template is pretty straightforward. Given you have two separate arrays, you can do the following:

const sixThings = [1, 2, 3, 4, 5, 6]

const weekdays = ['mon', 'tue', 'wed']

<div class="row" *ngFor="let thing of sixThings"> <-- **repeated 6 times**
    <div class="col-md-auto" *ngFor="let weekday of weekdays"> <-- **repeated 7 times**
    </div>
</div>

I'll update the answer later for the case where you have a nested array already, or can compose one.

查看更多
登录 后发表回答