You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Angular FlexLayout让*NgFor生成内容按每行3个排列

解决*NgFor元素每行3个排列的问题

方法一:基于Angular Flex Layout实现

你当前的fxLayout="row"默认不会自动换行,只需添加换行属性并设置每个卡片的宽度占比,就能实现每行3个的布局:

<div fxLayout="row" fxLayoutWrap>
  <mat-card *ngFor="let item of cont" fxFlex="33.33%">
    <p>{{item.title}}</p>
  </mat-card>
</div>

如果需要给卡片之间添加间距,可以配合间距属性和调整宽度计算:

<div fxLayout="row" fxLayoutWrap fxLayoutGap="16px">
  <mat-card *ngFor="let item of cont" fxFlex="calc(33.33% - 16px)">
    <p>{{item.title}}</p>
  </mat-card>
</div>

方法二:使用原生CSS Grid布局

如果不依赖Flex Layout,用CSS Grid更简洁:

<div class="card-container">
  <mat-card *ngFor="let item of cont">
    <p>{{item.title}}</p>
  </mat-card>
</div>

对应的CSS样式:

.card-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

方法三:通过NgFor索引手动分组换行

利用*NgFor的index变量,每3个元素生成一个新行容器,适合需要对整行做特殊处理的场景:

<div *ngFor="let item of cont; let i = index">
  <div fxLayout="row" *ngIf="i % 3 === 0">
    <mat-card *ngFor="let subItem of cont.slice(i, i+3)">
      <p>{{subItem.title}}</p>
    </mat-card>
  </div>
</div>

内容的提问来源于stack exchange,提问作者Ann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:40:42