Am通过动态准备列将数据绑定到角材料表。
please find below code
component.ts
export class DepComponent {
tableSource :any= [
{
"name":"ssit",
"departments":[{"depName":"cse","noOfStudents":30},
{"depName":"civil","noOfStudents":60}]
},
{
"name":"vbit",
"departments":[{"depName":"cse","noOfStudents":90},
{"depName":"civil","noOfStudents":40}]
}
];
displayedColumns: string[] = [];
constructor() {
this.displayedColumns= this.tableSource[0].departments.map(x=>x.depName)
}
}
<table mat-table [dataSource]="tableSource" class="mat-elevation-z8">
<ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
<th mat-header-cell *matHeaderCellDef>
{{column}}
</th>
<td mat-cell *matCellDef="let element">
<span *ngFor="let s of element.departments">
{{s.noOfStudents}}
</span>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
这样获得输出,重复的数据在下面的每一行打印,并带有我的代码
cse civil
30 60 30 60
90 40 90 40
我想要类似下面的输出
Cse Civil
30 60
90 40
答案 0 :(得分:2)
要获得所需的结果,首先您需要将数据转换为所需的格式,例如
dataSource=this.tableSource.map(i=> {
var result = {};
i.departments.forEach(d=>{
result[d['depName']]=d.noOfStudents
})
return result;
})
然后将html更改为
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="cse">
<th mat-header-cell *matHeaderCellDef> Cse </th>
<td mat-cell *matCellDef="let element"> {{element.cse}} </td>
</ng-container>
<ng-container matColumnDef="civil">
<th mat-header-cell *matHeaderCellDef> Civil </th>
<td mat-cell *matCellDef="let element"> {{element.civil}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>