我有一个数组。我在Angular中用*ngFor显示它的项目。我需要它显示在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>
发布于 2021-05-19 18:41:49
如果有两行且元素的大小是固定的,则可以使用位置绝对
<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
};
});The .css
.wrapper{
position:relative;
}
.item{
position:absolute;
width: 150px;
height: 300px;
background-color: pink;
}the stackblitz
如果我们唯一需要的是像这样的“网格”,更新
1 2 3
4 5 6我们只能使用css flex (我一直推荐这个link about 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
}看看我们需要“修复”包装器的高度和溢出隐藏。
一个变量“页面”和一个变量“页面大小”(以及一个变量"numPages")允许我们“分页”。
我在ViewChild中使用模板引用变量"wrapper“,在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并添加了更改
发布于 2021-05-19 19:37:18
您可以像这样使用CSS Grid来完成此操作:
.item {
width: 150px;
height: 300px;
background-color: pink;
}
:host {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
grid-template-rows: 1fr 1fr;
grid-gap: 20px;
}这将根据屏幕大小动态地将所有内容放在2行中。但由于items固定了150px,在小屏幕上它会扩展到更多的行来显示所有内容。尝试调整窗口大小并检查结果。
下面是一个工作示例:https://stackblitz.com/edit/angular-ivy-zuvpxg?file=src/app/hello.component.css
https://stackoverflow.com/questions/67599499
复制相似问题