我正在开发一个 POC,使用 angular8 作为前端,SpringBoot 作为后端。我的后端函数返回一个包含动态键和值的 Map 对象列表 ( List < Map < String, Object > >
)。
我需要在前端 Angular 中使用 mat-dialog-content 中的 mat-table 来使用这个 map 数组。我坚持将键和值定义为 mat 表所需的属性。请帮助我填充 map 对象的动态列表(列标题作为 map 键,行作为 map 值)。
在下面发布我的组件和 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>
此时我收到以下错误: 错误:提供了重复的列定义名称:“column”。
我在组件中填充了映射数组,其中包含字符串和字符串值的映射。但是html中的实现逻辑并不完整,如果有人能指导我如何在mat表中填充 map 数据,那将非常有帮助。
PS:我已经迭代了 mat-dialog-content 中的映射数组,以便获取 mat-table 中的每个映射对象,以便映射键和值应填充为每个 mat-table 列标题和每个内的行垫对话框内容。
下面是数据示例
[
{
"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 |键
,其中管道是:
@Pipe({ name: 'keys' })
export class EnumToArrayPipe implements PipeTransform {
transform(data: {}) {
return Object.keys(data);
}
}
关于angular - 将 map 对象(具有动态键和值)渲染为 Angular 垫表(列和行作为 map 的键和值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614841/