我正在尝试动态添加Angular 2数据表(https://material.angular.io/components/table/overview)的行 . 我有一个服务("ListService"),它给我显示的列("meta.attributes"),我可以从中检索我的数据 .
问题是,如果我稍后更改显示的列,在我加载dataSource并且meta.attributes数组获取条目(因此行应该存在于html中)之后,它会给我这个错误:
Error: cdk-table: Could not find column with id "id".
看起来 Headers 找不到给定的行 . 有什么想法解决这个问题?
.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
感谢帮助!
2 回答
我能够通过一种解决方法来修复它......我刚刚在表中添加了一个* ngIf,并在服务(meta)完成加载时启用了所有内容 .
我有同样的问题,它没有显示 . 我通过在类中添加一个空构造函数来解决它:
constructor(){}
或者它不会正确设置表