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) {
      } 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)

How to use this code

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

    .. all your other attrs..
    .. all your other attrs..

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