Reputation: 437
I am trying to set autosize columns by default with AG-Grid and angular framework. so i have used gridColumnApi.autoSizeColumns
with click event and It's work fine. but when i try use this.autoSizeAll()
with ngOnInit() to set autosize columns by defaulti get this error Cannot read property 'getAllColumns'
i don't know what is the best way which i can autosize columns by default without click button?
<button (click)="autoSizeAll(false)">Auto-Size All</button>
<ag-grid-angular
style="width: 900px; height: 700px;"
class="ag-theme-balham"
[rowData]="rowData"
[defaultColDef]="defaultColDef"
[columnDefs]="columnDefs"
(firstDataRendered)="onFirstDataRendered($event)"
(gridReady)="onGridReady($event)">
</ag-grid-angular>
ngOnInit(){
this.autoSizeAll();
}
autoSizeAll() {
const allColumnIds = [];
// tslint:disable-next-line:only-arrow-functions
this.gridColumnApi.getAllColumns().forEach(function(column) {
allColumnIds.push(column.colId);
});
this.gridColumnApi.autoSizeColumns(allColumnIds);
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.http
.get(
'https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinnersSmall.json'
)
.subscribe(data => {
this.rowData = data;
});
}
}
here is the plunker
Upvotes: 6
Views: 10463
Reputation: 4578
The best way I found is by using the modelUpdated
event:
<ag-grid-angular
style="width: 900px; height: 700px;"
class="ag-theme-balham"
[rowData]="rowData"
[defaultColDef]="defaultColDef"
[columnDefs]="columnDefs"
(firstDataRendered)="onFirstDataRendered($event)"
(gridReady)="onGridReady($event)"
(modelUpdated)="onModelUpdated()">
</ag-grid-angular>
onModelUpdated() {
this.autoSizeAll();
}
Upvotes: 1
Reputation: 1997
You are calling the function before it even has initialized the gridColumnApi
. Try to call this.autoSizeAll()
in the onGridReady
function after you have initialized this.gridColumnApi
.
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.autoSizeAll(); // do your autosizing here
this.http
.get(
'https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinnersSmall.json'
)
.subscribe(data => {
this.rowData = data;
});
}
Upvotes: 3