Skip to content

Automatically Resize All Columns to Fit in Ag-Grid

If you have an Ag-Grid, and want to automatically resize all the columns to fit the width of the viewport, you can use this hack.

The implementation

/** * resizes the columns to fit the width of the grid * @param allowShrink if false, columns will NOT be resized when there is no "empty" horizontal space * */ public resizeColumnsToFit(allowShrink = true) { if (this.gridApi) { if (allowShrink) { this.gridApi.sizeColumnsToFit(); } else { /** * this is a "hacK" - there is no way to check if there is "empty" space in the grid using the * public grid api - we have to use the internal tools here. * it could be that some of this apis will change in future releases */ const panel = this.gridApi["gridPanel"]; const availableWidth = this.gridApi["gridPanel"].eBodyViewport.clientWidth; const columns = this.gridApi["gridPanel"]["columnController"].getAllDisplayedColumns(); const usedWidth = this.gridApi["gridPanel"]["columnController"].getWidthOfColsInList(columns); if (usedWidth < availableWidth) this.gridApi.sizeColumnsToFit() } } }
Code language: TypeScript (typescript)

How to use this code

Make sure that the following is in your HTML, to trigger the onRowDataChanged event:

<ag-grid-angular .. all your other attrs.. (rowDataChanged)="onRowDataChanged($event)" (firstDataRendered)="onRowDataChanged($event)" .. all your other attrs.. ></ag-grid-angular>
Code language: HTML, XML (xml)

Then create the following function to handle the trigger:

// Use the onRowDataChanged(params) { setTimeout(() => { this.resizeColumnsToFit() // call our implementation this.gridColumnApi?.autoSizeColumn('Name') // override autosizing for individual columns }); }
Code language: TypeScript (typescript)

See also  Add TinyMCE code button
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x