使用Angular + ngFor/ng-template遍历数组时如何嵌套html? [英] How to nest html when looping through array using Angular + ngFor / ng-template?
问题描述
我正在尝试以以下格式为数组输出html
I'm trying to output html in the following format for an array
weekDaysHeaderArr
的长度为42 = 6 x 7.
weekDaysHeaderArr
whose length is 42 = 6 x 7.
换句话说,我想像这样将每7列div元素嵌套在一个行div(共6个)中.
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>
我可以使用ngFor
明显地产生相同的html元素(div class="col-md-auto">
)42次,但是如何将每7个元素嵌套在<div class="row">
中呢?
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">
?
我以前没有使用过ng-template
和ng-container
,也无法理解文档,可以使用它们来做到这一点吗?据我所知,它们是为在html元素之间切换而不是嵌套而设计的.
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.
推荐答案
从您的数组创建矩阵
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>
这篇关于使用Angular + ngFor/ng-template遍历数组时如何嵌套html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!