我正在嘗試動態添加角度2數據表(https://material.angular.io/components/table/overview)的行。 我得到一個服務(「ListService」),它給了我顯示列(「meta.attributes」),我可以從中檢索我的數據。帶動態行的角度2材料數據表
的問題是,如果我改變顯示的列後,當我加載的數據源和與meta.attributes陣列獲取一個條目(所以應該排在html存在),它給了我這個錯誤:
Error: cdk-table: Could not find column with id "id".
看起來像標題找不到給定的行。任何想法來解決這個問題?
.html文件:
<md-table #table [dataSource]="dataSource" mdSort>
<ng-container *ngFor="let attr of meta.attributes">
<ng-container [cdkColumnDef]="attr.name">
<md-header-cell *cdkHeaderCellDef md-sort-header>{{attr.label}}</md-header-cell>
<md-cell *cdkCellDef="let row">
{{row[attr.name]}}
</md-cell>
</ng-container>
</ng-container>
<md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
<md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
的.ts文件:
export class ListComponent implements OnInit {
displayedColumns = [];
exampleDatabase = new ExampleDatabase();
dataSource: ExampleDataSource | null;
meta: any = {
attributes: []
};
constructor(private service: ListService) {
//If i do it here it works
//this.meta.attributes.push({label: "ID", name: "id"});
}
ngOnInit() {
this.dataSource = new ExampleDataSource(this.exampleDatabase);
this.service.getMeta(this.name).subscribe(meta => {
//not here
this.meta.attributes.push({label: "ID", name: "id"});
this.service.getTableData(this.name).subscribe(data => {
this.exampleDatabase.loadData(data);
let cols = [];
for (let i = 0; i < this.meta.attributes.length; i++)
cols.push(this.meta.attributes[i].name);
this.displayedColumns = cols;
});
});
}
}
...exampleDatabase etc., same as from Angular Website
感謝您的幫助!
已經從'@ angular/cdk'導入'import {DataSource};'? – nmanikiran
是的,我做到了。我的DataSource應該幾乎可以,如果我不更新構造函數或onInit之後顯示的列,則會顯示錶。這個問題應該更像是md-header沒有注意到這個表有新的html元素或者某事。類似... –