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

Angular中mat-grid与mat-card无法渲染数据问题求助

问题排查与修复方案

核心问题分析

  1. 数组越界错误:tiles数组中尝试访问this.BOATS[2],但BOATS仅包含2个元素(索引0和1),导致初始化时抛出错误,中断组件渲染。
  2. Mat-Card结构错误:船只名称和图片被放置在mat-card外部,mat-card-image指令必须作为mat-card的直接子元素才能生效。
  3. 本地图片路径无效:Torvang的图片路径使用了反斜杠,Angular中本地资源路径需使用正斜杠,且需确保路径指向正确的资源位置。
  4. TypeScript接口命名不规范:boat接口未遵循PascalCase命名约定,可能引发潜在的类型识别问题。

修复后的代码

1. TypeScript代码(boats.component.ts)

import { Component, OnInit } from '@angular/core';

export interface Tile {
  cols: number;
  rows: number;
  text: string;
}

// 修正接口命名为PascalCase
export interface Boat {
  id: number;
  name: string;
  img: string;
}

@Component({
  selector: 'app-boats',
  templateUrl: './boats.component.html',
  styleUrls: ['./boats.component.css']
})

export class BoatsComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  BOATS: Boat[] = [
    {id: 1, name: "FreiFjord", img: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS6n30OrfVjAS0mXcTN6xoZSOpFxuxJxXYLbPELBKZZJg&s"},
    // 修正本地图片路径为正斜杠(假设图片在assets目录下)
    {id: 2, name: "Torvang", img: "./assets/torhusshipping/torvang.jpg"},
  ]

  // 修正数组索引,使用有效范围的索引值
  tiles: Tile[] = [
    {text: this.BOATS[0].name, cols: 1, rows: 1},
    {text: this.BOATS[1].name, cols: 1, rows:1},
  ]

}

2. HTML代码(boats.component.html)

<mat-grid-list cols="2" rowHeight="2:1">
    <mat-grid-tile *ngFor="let boat of BOATS">
        <mat-card>
            <mat-card-title>{{boat.name}}</mat-card-title>
            <img mat-card-image [src]="boat.img">
        </mat-card>
    </mat-grid-tile>
</mat-grid-list>

额外检查项

确保你的Angular模块中已导入所需的Material组件模块:

import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';

@NgModule({
  imports: [
    // 其他模块
    MatGridListModule,
    MatCardModule
  ]
})
export class YourModuleName { }

内容的提问来源于stack exchange,提问作者Thomas Olsen Tangen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:21