https://stackblitz.com/edit/dynamic-columns-mat-table
这就是我到目前为止所拥有的。
该表完美呈现,但我的要求是我事先不知道列名,所以我需要提及列名,例如
而不是 ${element.description} => ${element.elementname}
或者
${element.description} => ${element.'description'}
任何建议,将不胜感激。谢谢你。
HTML
<mat-table #table [dataSource]="dataSource">
<ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
<mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
<mat-cell *cdkCellDef="let row">{{ column.cell(row) }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
组件.ts
export class DataPageComponent implements OnInit,AfterViewInit {
columns = [
{ columnDef: 'Gender', header: 'Gender', cell: (element: any) => `${element.Gender}` },
{ columnDef: 'VechiclesOwned', header: 'Vechicles Owned', cell: (element: any) => `${element.VechiclesOwned}` },
{ columnDef: 'description', header: 'description', cell: (element: any) => `${element.description}` },
];
displayedColumns = this.columns.map(c => c.columnDef);
dataSource = new FormDataSource(this.af);
constructor(public af: AngularFireDatabase) { }
}
export class FormDataSource extends DataSource<any>{
constructor(private af: AngularFireDatabase){
super()
}
connect():Observable<any[]>{
return this.af.list('/data');
}
disconnect() {}
}