Angular中mat-Table绑定嵌套对象时如何拆分solde到不同列
问题核心原因
你当前的实现是将所有月份的solde值都渲染在同一个mnth列下,所以会挤在同一列。mat-table的每一列都需要对应独立的matColumnDef定义,你需要动态生成每个月份对应的列配置即可实现需求。
具体修改步骤
1. 修改TS组件代码
调整列配置逻辑,动态拼接固定列和月份动态列:
export class CompacteComponent { // 预设固定列 fixedColumns: string[] = ['collaborator', 'cetCP', 'cetRTT', 'perteRTT', 'perteCP']; // 最终渲染的全量列 displayColumns: string[] = []; // 存储全局月份列表 monthList: Month[] = []; dataSource :visionCompacteDTOs[] = []; constructor(private reportingService:ReportingService) { } ngOnInit():void { this.reportingService.getNews().subscribe((response)=>{ this.dataSource = response; if(response.length > 0) { // 提取月份列表(若不同用户月份不一致,需遍历所有用户mnth数组去重) this.monthList = response[0].mnth; // 生成动态月份列名 const monthColumns = this.monthList.map(month => `solde_${month.month}`); // 合并固定列和动态列 this.displayColumns = [...this.fixedColumns, ...monthColumns]; } }, (error)=>{ console.log("Error Occured: "+error); } ) } // 工具方法:根据行数据和月份名获取对应solde值 getSoldeByMonth(element: visionCompacteDTOs, monthName: string): number { const targetMonth = element.mnth.find(m => m.month === monthName); return targetMonth ? targetMonth.solde : 0; } }
2. 修改HTML模板代码
删除原有统一的mnth列,改为动态生成每个月份的独立列:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 lftm"> <!-- 固定列:员工 --> <ng-container matColumnDef="collaborator"> <th mat-header-cell *matHeaderCellDef> 员工 </th> <td mat-cell *matCellDef="let element"> {{element.collaborator}} </td> </ng-container> <!-- 固定列:cetCP --> <ng-container matColumnDef="cetCP"> <th mat-header-cell *matHeaderCellDef > cetCP </th> <td mat-cell *matCellDef="let element"> {{element.cetCP}} </td> </ng-container> <!-- 固定列:cetRTT --> <ng-container matColumnDef="cetRTT"> <th mat-header-cell *matHeaderCellDef > cetRTT </th> <td mat-cell *matCellDef="let element"> {{element.cetRTT}} </td> </ng-container> <!-- 动态生成月份列,替换原有的mnth列 --> <ng-container *ngFor="let month of monthList" [matColumnDef]="'solde_' + month.month"> <th mat-header-cell *matHeaderCellDef >{{month.month}}</th> <td mat-cell *matCellDef="let element"> {{getSoldeByMonth(element, month.month)}} </td> </ng-container> <!-- 固定列:Perte RTT --> <ng-container matColumnDef="perteRTT"> <th mat-header-cell *matHeaderCellDef class="prt"> Perte RTT </th> <td mat-cell *matCellDef="let element"> {{element.perteRTT}} </td> </ng-container> <!-- 固定列:Perte CP --> <ng-container matColumnDef="perteCP"> <th mat-header-cell *matHeaderCellDef class="prt"> Perte CP </th> <td mat-cell *matCellDef="let element"> {{element.perteCP}} </td> </ng-container> <!-- 绑定动态生成的列配置 --> <tr mat-header-row *matHeaderRowDef="displayColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayColumns;"></tr> </table>
注意事项
如果不同用户的月份列表存在差异,需要先遍历所有dataSource条目,收集所有出现过的月份去重后再生成monthList,避免部分数据展示缺失。另外注意Month类中month字段的类型定义和实际返回的字符串格式匹配,避免查找匹配失败。
内容的提问来源于stack exchange,提问作者adam
相关产品推荐
相关产品推荐

