我正在尝试使用自定义标题创建动态角度材料表,我打算稍后将其用于验证表的样式。我可以成功显示tableHeaders,但是在显示tableData方面没有成功。没有错误。我是Angular的初学者,所以我们将不胜感激,谢谢!
TS:
export class DataTableComponent implements OnInit {
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
@ViewChild(MatSort, { static: true }) sort: MatSort;
dataSource
tableHeader = [
{
name: 'id',
displayName: 'ID',
type: 'number'
},
{
name: 'name',
displayName: 'Name',
type: 'number'
},
{
name: 'age',
displayName: 'Age',
type: 'number'
},
];
tableData = [
{
id: 1,
name: 'Bogart',
age: 10,
},
{
id: 2,
name: 'John',
age: 20,
},
{
id: 3,
name: 'Mark',
age: 30,
}
];
constructor() { }
ngOnInit() {
this.dataSource = new MatTableDataSource(this.tableData);
this.dataSource.sort = this.sort;
}
objectKeys(obj) {
return Object.keys(obj);
}
}
HTML:
<table mat-table class="lmat-elevation-z8" [dataSource]="dataSource" matSort matSortActive="id"
matSortDirection="asc" matSortDisableClear>
<ng-container [matColumnDef]="tableData" *ngFor="let tableData of objectKeys(tableHeader)">
<th mat-header-cell *matHeaderCellDef mat-sort-header>
<!--arrowPosition="before" -->
{{tableHeader[tableData].displayName}}
</th>
<td mat-cell *matCellDef="let element" class="mat-column-vinCode">
{{element[tableData]}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="objectKeys(tableHeader); sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: objectKeys(tableHeader)"></tr>
</table>
</div>
<div class="mat-table__bottom mat-table__bottom--padding">
<mat-spinner [diameter]="20" *ngIf="dataSource.loading$ | async"></mat-spinner>
<mat-paginator [pageSize]="6" [pageSizeOptions]="[3, 6, 15]" [length]="dataSource.paginatorTotal$ | async"
[showFirstLastButtons]="true"></mat-paginator>
</div>
表格:
答案 0 :(得分:-1)
您使用objectKeys(obj) {return Object.keys(obj);}
,这是错误的
您可以直接遍历tableHeader:
<!--see that use tableData.displayName to see the "header"-->
<ng-container [matColumnDef]="tableData.name" *ngFor="let tableData of tableHeader>
<th mat-header-cell *matHeaderCellDef mat-sort-header>
{{tableData.displayName}}
</th>
<!--and element[tableData.name] so see the field-->
<td mat-cell *matCellDef="let element" class="mat-column-vinCode">
{{element[tableData.name]}}</td>
</ng-container>
您需要使用
作为列 getColumns(obj:any) {
return obj.map(x=>x.name);
}
<tr mat-header-row *matHeaderRowDef="getColumns(tableHeader); sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: getColumns(tableHeader)"></tr>