我创建了一个 HTML 表,它将生成无限的columns基于
数量rows在输入数据中。我尝试过使用这个帖子 https://stackoverflow.com/questions/49868019/angular-material-table-dynamic-columns-without-model举个例子,但我正在努力将 HTML 转换为 Angular Material 设计。有什么建议么?
StackBlitz 演示 https://stackblitz.com/edit/angular-iga2fk
由于 Angular 材质表是基于列的(并且我找不到迭代其中行的方法),所以我很快就陷入了困境。
我无法在 StackBlitz 中获得有角度的材料表,所以这里是我的代码的复制粘贴:
<table mat-table [dataSource]="newLicenseDS">
<ng-container *ngFor="let disCol of newLicCol; let idx = index" matColumnDef="{{disCol}}">
<th mat-header-cell *matHeaderCellDef>{{disCol}}</th>
<ng-container *ngIf="idx==0">
<td mat-cell *matCellDef="let e">{{e[0]|json}}</td>
</ng-container>
<ng-container *ngIf="idx==1">
<td mat-cell *matCellDef="let e">{{e[1]|json}}</td>
</ng-container>
<ng-container *ngIf="idx==2">
<td mat-cell *matCellDef="let e[2]">{{e|json}}</td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="newLicCol"></tr>
<tr mat-row *matRowDef="let row; columns: newLicCol"></tr>
</table>
您唯一需要的是“循环”matColumnDef。 -看到我们使用[matColumnDef]
and {{element[col]}}
如果你的桌子是这样的
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let col of displayedColumns" [matColumnDef]="col">
<th mat-header-cell *matHeaderCellDef>{{col}}</th>
<td mat-cell *matCellDef="let element"> {{element[col]}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
您只需要转换数据并指示显示的列。
你可以在 ngOnInit() 中执行
ngOnInit() {
const head = this.data.map(x => x.name)
const data: any[] = [];
this.data.forEach((x, index) => {
Object.keys(x).forEach((k, index2) => {
data[index2] = data[index2] || {}
data[index2][head[index]] = x[k]
})
})
this.displayedColumns=head;
this.dataSource = data.slice(1); //I remove the first element that was the "header"
}
See in 堆栈闪电战 https://stackblitz.com/edit/angular-8nmwlq?file=app%2Ftable-basic-example.ts
Update关于这个问题,不要使用 mat-table,而是使用简单的表,只是我们需要使用 displayedColumns 进行迭代。有些喜欢
<table>
<tr>
<th *ngFor="let col of displayedColumns">{{col}}</th>
</tr>
<tr *ngFor="let row of dataSource">
<td *ngFor="let col of displayedColumns">{{row[col]}}</td>
</tr>
</table>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)