使用Angular Material Grid List展示网格列表时出现运行错误
问题解决方法
核心问题分析
错误提示mat-grid-list: must pass in a column number through cols.的本质是未遵循Angular Material Grid List的组件结构要求:mat-grid-list的直接子元素必须是mat-grid-tile组件,你直接将带*ngFor的<a>标签作为子元素,同时缺失了MatGridTileModule的导入。
具体修复步骤
1. 修正HTML结构,用mat-grid-tile包裹网格项
mat-grid-list要求每个网格项必须由mat-grid-tile承载,修改后的代码如下:
<mat-grid-list cols="3" class="border-list specials-list"> <mat-grid-tile *ngFor="let item of specials; index as i"> <a [href]="item?.link"> <img [src]="item.src" [alt]="item.title" /> <span class="image-title">{{ item.title }}</span> </a> </mat-grid-tile> </mat-grid-list>
2. 导入缺失的MatGridTileModule
在组件的imports数组中添加MatGridTileModule,因为mat-grid-tile组件由该模块提供:
@Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], imports: [ CommonModule, MatGridListModule, MatGridTileModule, // 新增该行 MatToolbarModule, NgbModule, MatDialogModule, ], standalone: true, }) export class HomeComponent { constructor(private dialog: MatDialog) {} specials: AppListModel[] = [ { title: 'x', src: '../../assets/images/logos/irancell.png', link: 'https://cdn-ngmy.irancell.ir/app/MyIrancell.apk', }, { title: 'y', src: '../../assets/images/logos/Okala.jpg', link: 'https://trc.metrix.ir/dueaid/?Token=%7BToken%7D', } ]; }
3. 可选:规范cols绑定方式(符合Angular最佳实践)
若列数为固定值,cols="3"可正常使用;若需动态控制列数,建议使用方括号绑定:
<mat-grid-list [cols]="3" class="border-list specials-list">
验证修复
修改完成后重启项目,错误会消失,网格列表将按3列布局展示项目内容。
内容的提问来源于stack exchange,提问作者heliya rb
相关产品推荐
相关产品推荐

