How to nest html when looping through array using Angular + ngFor / ng-template?

半腔热情 提交于 2019-12-11 18:26:36

问题


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.


回答1:


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>



回答2:


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.




回答3:


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];


来源:https://stackoverflow.com/questions/55808819/how-to-nest-html-when-looping-through-array-using-angular-ngfor-ng-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!