将地图对象(具有动态键和值)呈现为角度垫表(列和行作为地图的键和值)

  • 本文关键字:键和值 地图 对象 动态 angular mat-table
  • 更新时间 :
  • 英文 :


我正在使用angular8作为前端和SpringBoot作为后端开发POC。我的后端函数返回一个具有动态键和值的 Map 对象列表 (List < Map < String, Object >>(。 我需要在 mat-dialog-content 中使用 mat-table 在前端角度中使用此地图数组。我坚持将键和值定义为 mat 表的必需属性。请帮助我填充地图对象的动态列表(列标题作为地图键,行作为地图值(。

在下面发布了我的组件和 html 文件:

元件:

export class ProfileDialogComponent {
username: String = "";
mapArray: Map < String, Object > [] = [];
constructor(private dialogRef: MatDialogRef < ProfileDialogComponent > ,
@Inject(MAT_DIALOG_DATA) data, private userService: UserService) {
this.username = data.username;
this.userService.getImportedUserCareer(this.username).subscribe(data => {
this.mapArray = data;
});
}
}

.html:

<div>
<mat-dialog-content *ngFor="let map of mapArray">
<mat-table class="mat-elevation-z8" [dataSource]="map">
<ng-container matColumnDef="column" *ngFor="let column of map | keyvalue">
<mat-header-cell *matHeaderCellDef>{{column}}</mat-header-cell>
<mat-cell *matCellDef="let element">{{element[column]}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="map"></mat-header-row>
<mat-row *matRowDef="let row; columns: map"></mat-row>
</mat-table>
</mat-dialog-content>
</div>

此时,我收到以下错误: 错误:提供的列定义名称重复:"列"。

我在我的组件中填充了带有字符串和字符串值映射的映射数组。但是html中的实现逻辑并不完整,如果有人可以指导我如何在mat表中填充地图数据,那将非常有帮助。

PS:我已经迭代了mat-dialog-content中的map数组,以便我在mat-table中获取每个map对象,以便map键和值应该填充为每个mat-table列标题和每个mat-dialog内容中的行。

以下是数据示例

[
{
"Test Matches": 320,
"Runs": 17500,
"High Score": 242,
"Batting Avg": 65.42,
"Wickets": 14,
"Bowling Avg": 31.76,
"Best Bowling": "1/34",
"Catches": 173,
"MoS": 25
},
{
"ODI Matches": 150,
"Runs": 15750,
"High Score": 184,
"Batting Avg": 62.75,
"Catches": 173,
"MoM": 54
}
]

请帮忙!

谢谢 希哈德

以下模板应该适合您:

<div *ngFor="let map of mapArray">
<mat-table class="mat-elevation-z8" [dataSource]="[map]">
<ng-container [matColumnDef]="column.key" *ngFor="let column of map | keyvalue">
<mat-header-cell *matHeaderCellDef>{{ column.key }}</mat-header-cell>
<mat-cell *matCellDef="let element">{{ column.value }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="({}).constructor.keys(map)"></mat-header-row>
<mat-row *matRowDef="let row; columns: ({}).constructor.keys(map)"></mat-row>
</mat-table>
</div>

堆栈闪电战示例

请注意,为了获得更好的性能,您可以将({}).constructor.keys(map)替换为您自己的自定义管道,如管道所在的map | keys

@Pipe({ name: 'keys' })
export class EnumToArrayPipe implements PipeTransform {
transform(data: {}) {
return Object.keys(data);
}
}

最新更新