html - ngFor 限制行
问题描述
我有一个数组。*ngFor
我用Angular展示它的项目。我需要它显示在 2 行中,列数尽可能多。它可能只显示其中的 6 个,但没关系。
.item {
width: 150px;
height: 300px;
background-color: pink;
}
<div *ngFor="let item of [1,2,3,4,5,6,7,8,9,10]">
<div class="col item">{{item}}</div>
</div>
解决方案
如果有两行并且元素的大小是固定的,则可以使用绝对位置来获取它
<div class="wrapper">
<ng-container *ngFor="let item of items;let i=index">
<div class="item" [ngStyle]="style[i]">{{item}}</div>
</ng-container>
</div>
编码:
items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
//if 1 2 3 4 5
// 6 7 8 9
style = this.items.map((_, index) => {
const top = Math.floor((2 * index) / this.items.length);
const left = index % Math.floor((this.items.length + 1) / 2);
return {
top: top ? top * 300 + 'px' : 0,
left: left ? left * 150 + 'px' : 0
};
});
//if 1 3 5 7 9
// 2 4 6 8
style2 = this.items.map((_, index) => {
const top = index%2;
const left = Math.floor((index/2));
return {
top: top ? top * 300 + 'px' : 0,
left: left ? left * 150 + 'px' : 0
};
});
.css
.wrapper{
position:relative;
}
.item{
position:absolute;
width: 150px;
height: 300px;
background-color: pink;
}
堆栈闪电战
如果我们唯一需要的是“网格”,请更新
1 2 3
4 5 6
我们只能通过 css flex 获得它(我一直推荐这个关于 css-flex 的链接)
.wrapper-flex
{
display:flex;
flex-direction:row;
flex-wrap:wrap;
height:204px;
width:100%; //<--neccesary to paginate
overflow:hidden;
}
.wrapper-flex .item{
position:relative
}
看到我们需要“修复”包装器和溢出隐藏的高度。
变量“page”和变量“page-size”(以及变量“numPages”)允许我们“分页”
我在 ViewChild 中使用模板引用变量“包装器”,并在 ngAfterViewInit 中订阅事件 window.resize
page=0;
pageSize=this.items.length;
numPages=1
ngAfterViewInit(){
setTimeout(()=>{
fromEvent(window,'resize').pipe(
startWith(null)
).subscribe(_=>{
const width=this.wrapper.nativeElement.getBoundingClientRect().width
this.pageSize=Math.floor(width/150)*2;
this.numPages=Math.floor(this.items.length/this.pageSize)
this.page=0;
})
})
}
注意:我更新了 stackblitz 添加了更改