我正在尝试在组件加载时将数据加载到ag-grid中。 结合example on ag-grid github和answer to this question我有这个ngOnInit作为我的组件:
ngOnInit(): void {
this.promisesService.getPromises()
.subscribe((s: Promise[]) => {
console.log('got response:', s);
this.gridOptions = {
enableSorting: true,
rowData: this.createRowData(),
columnDefs: this.createColumnDefs(),
onGridReady: () => {
this.gridOptions.api.sizeColumnsToFit();
console.log('ag-grid ready');
}
};
console.log('options set:', this.gridOptions);
});
}
网格卡在"正在加载......"没有错误消息。 gridOptions设置正确,其rowData包含我期望看到的所有数据。 但是,从不触发onGridReady。
如果我在subscribe之外移动选项的设置,它可以正常工作:
ngOnInit(): void {
this.promisesService.getPromises()
.subscribe((s: Promise[]) => {
console.log('got response:', s);
console.log('options set:', this.gridOptions);
});
this.gridOptions = {
enableSorting: true,
rowData: this.createRowData(),
columnDefs: this.createColumnDefs(),
onGridReady: () => {
this.gridOptions.api.sizeColumnsToFit();
console.log('ag-grid ready');
}
};
}
在模板中我只设置选项:
<ag-grid-ng2 #agGrid style="width: 100%; height: 200px;" class="ag-fresh" [gridOptions]="gridOptions"></ag-grid-ng2>
我已经尝试将代码移动到构造函数中并在模板中设置rowData,但它没有帮助。
我错过了什么?
由于
答案 0 :(得分:0)
由于某种原因,如果我在构造函数中设置选项并在Init中保留数据,它可以正常工作。任何人都知道原因,请让我知道:
export class PromisesListComponent {
private gridOptions: GridOptions;
promises: Promise[];
constructor(private promisesService: PromisesService) {
this.gridOptions = {
rowData: this.promises,
columnDefs: this.createColumnDefs(),
enableColResize: true,
enableSorting: true,
enableFilter: true,
onGridReady: () => {
this.gridOptions.api.sizeColumnsToFit();
}
}
}
ngOnInit(): void {
this.promisesService.getPromises()
.subscribe((response: Promise[]) => {
this.promises = response;
});
}
private createColumnDefs() {
return [
{
headerName: "Agreement Code",
field: "AgreementCode",
width: 200
}
];
}
}