ag grid sizeColumnsToFit for columns not working

Poonam Thote picture Poonam Thote · Feb 28, 2017 · Viewed 31.3k times · Source

I have used ag-grid ng2 and trying to apply sizeColumnsToFit. For example: If there are 4 columns then it should be automatically resized and fit to the width of grid. gridOptions.api.sizeColumnsToFit() not working.

var gridOptions = {
    columnDefs: columnDefs,
    rowData: null,
    enableColResize: true
};

this.columnDefs = [
     {headerName: "Age", field: "age", width: 90, minWidth: 50, maxWidth: 100},
    {headerName: "Country", field: "country", width: 120},
    {headerName: "Year", field: "year", width: 90},
    {headerName: "Date", field: "date", width: 110}


    ];

 gridOptions.api.sizeColumnsToFit();

Answer

bensonissac picture bensonissac · Dec 20, 2017

Try this code.. while defining columnDefs set suppressSizeToFit: false for all fields,

this.columnDefs = [
 {headerName: "Age", field: "age", width: 90, minWidth: 50, maxWidth: 100,suppressSizeToFit: false},
 {headerName: "Country", field: "country", width: 120,suppressSizeToFit: false},
 {headerName: "Year", field: "year", width: 90,suppressSizeToFit: false},
 {headerName: "Date", field: "date", width: 110,suppressSizeToFit: false}
 ];

Then in onGridReady use the below code.

onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;   
params.api.sizeColumnsToFit(); 
}