Angular Material table内部循环渲染数据的实现问题
问题修复方案
核心错误点
*ngFor遍历对象错误:col.config.isPosition是布尔值true,无法作为可遍历的数组使用,你需要正确遍历Material Table绑定的数据源,或者对应字段内的数组- 图片路径取值和已验证的正常写法不一致:你循环外可运行的写法带了下标
[0],循环内的写法遗漏了该下标
代码修改参考
场景1:每行仅展示1张对应位置图(复用你已验证的路径写法)
<!-- 需确保你的mat-table已正确绑定数据源,例:<mat-table [dataSource]="dataSource"> --> <ng-container *ngFor="let col of columns" [matColumnDef]="col.key"> <mat-header-cell *matHeaderCellDef>{{col.display}}</mat-header-cell> <mat-cell *matCellDef="let element"> <ng-container *ngIf="col.config?.isPosition"> <img src="assets/{{element[col.key][0].position}}.jpg" alt="位置图"> </ng-container> <!-- 其他非图片列的展示逻辑可以在这里扩展 --> </mat-cell> </ng-container> <!-- 记得补全列渲染声明,示例如下 --> <mat-header-row *matHeaderRowDef="columns.map(item => item.key)"></mat-header-row> <mat-row *matRowDef="let row; columns: columns.map(item => item.key)"></mat-row>
场景2:每行遍历展示element[col.key]数组内的所有对应图片
<ng-container *ngFor="let col of columns" [matColumnDef]="col.key"> <mat-header-cell *matHeaderCellDef>{{col.display}}</mat-header-cell> <mat-cell *matCellDef="let element"> <ng-container *ngIf="col.config?.isPosition"> <div *ngFor="let item of element[col.key]"> <img src="assets/{{item.position}}.jpg" alt="位置图"> </div> </ng-container> </mat-cell> </ng-container>
TS配置补全参考
// 补全display属性即可正常使用 columns = [ {key: 'position', display: '位置展示', config : {isPosition:true}}, // 其他列的配置 ];
内容的提问来源于stack exchange,提问作者Herge
相关产品推荐
相关产品推荐

