Angular 6中如何用ngFor使生成的卡片保持横向排列?
解决Angular Flex布局卡片横向排列问题
我来帮你搞定这个Flex布局的问题!你现在的卡片之所以堆叠,核心问题是把fxLayout指令用在了*ngFor循环的元素上——这相当于每个卡片都被包裹在一个独立的布局容器里,自然会上下堆叠,而不是在同一行排列。
修正后的代码
<div fxFlex *ngIf="designs" [@expand] fxLayout="row wrap" fxLayoutGap="16px"> <div fxFlex="30" *ngFor="let design of designs"> <mat-card> <mat-card-header> <mat-card-title> <h2>{{design.label}}</h2> </mat-card-title> <mat-card-subtitle> <h3>{{design.time}}hr</h3> </mat-card-subtitle> </mat-card-header> <img mat-card-image src="{{BaseURL + design.image}}"> <mat-card-content> <p>{{design.description}}</p> </mat-card-content> <mat-card-actions style="margin: auto;"> <button mat-stroked-button routerLink="/contact" color="primary">Book Now</button> </mat-card-actions> </mat-card> </div> </div>
关键改动说明
- 把布局容器移到循环外层:将
fxLayout="row wrap"添加到最外层的div(带*ngIf的那个),这样所有卡片都处于同一个Flex布局容器中,会自动横向排列,空间不足时自动换行。 - 移除多余的布局指令:删掉
*ngFor元素上的fxLayout和style="display: inline",这些会干扰Flex布局的正常工作。 - 添加间距优化:新增
fxLayoutGap="16px"给卡片之间添加间距,让布局更美观(你可以根据需求调整数值)。
额外注意事项
确保你已经在项目中正确导入了Angular Flex Layout模块,在app.module.ts中需要包含:
import { FlexLayoutModule } from '@angular/flex-layout'; @NgModule({ imports: [ // ...其他模块 FlexLayoutModule ] }) export class AppModule { }
这样修改后,你的卡片应该就能正常横向排列,并且在小屏幕上自动适配换行啦!
内容的提问来源于stack exchange,提问作者Utkarsh
相关产品推荐
相关产品推荐

