Reputation: 451
Columns in ag-grid:
columnsDefs = [
{
headerName: 'Name',
field: 'name'
},
{
headerName: 'Age',
field: 'age'
},
{
headerName: 'Description',
field: 'description'
}
];
The characters length in description can vary. For example, some row might have just 10 characters and some row might have 50 characters. If I set the column width then, if description has much longer length of characters then some of characters will not be shown.
api.sizeColumnsToFit() will scale the columns to fit the available width of the screen. I wanted to achieve the column 'Description' width to be responsive based on the its row data.
Upvotes: 1
Views: 21401
Reputation: 31
If you are coming to this discussion looking for the width of your table to adaptively increase or decrease based on the current width of the browser, here's how you do it in react:
let width = 100
const onFirstDataRendered = (params) => {
params.api.sizeColumnsToFit();
};
const onGridSizeChanged = (params) => {
let columnCount = params.columnApi.columnModel.gridColumns.length
width = params.clientWidth / columnCount
params.api.sizeColumnsToFit();
};
return (
<div style={{ width: '100%', height: '100%' }}>
<div id="grid-wrapper" style={{ width: '100%', height: '263px' }}>
<div
id="myGrid"
style={{
height: '100%',
width: '100%',
}}
className="ag-theme-alpine-dark"
>
<AgGridReact
defaultColDef={{ resizable: true }}
onFirstDataRendered={onFirstDataRendered}
onGridSizeChanged={onGridSizeChanged}
rowData={rowData}
>
<AgGridColumn field="data" width={width}></AgGridColumn>
<AgGridColumn field={columnData[1].field} width={width}></AgGridColumn>
<AgGridColumn field={columnData[2].field} width={width}></AgGridColumn>
</AgGridReact>
</div>
</div>
</div>
);
};
Upvotes: 1
Reputation: 5649
To resize all the columns to the content width use:
columnApi.autoSizeAllColumns()
. But, call this method on firstDataRendered()
event. Also you can set suppressColumnVirtualisation=true
if you have many columns.
Explanation:
columnApi.autoSizeAllColumns()
method resizes the columns to wrap the content width of each column. But, for the grid to know what is the content width, it first has to render the data. So, this method should be called on firstDataRendered()
event. If the number of columns are more, then the columns which are behind the horizontal scrollbar does not render at once, because of lazy loading in ag-grid. So, autoSizeAllColumns()
can not resize those columns. For that, lazy loading needs to be disabled using suppressColumnVirtualisation=true
property of the grid.
Upvotes: 4