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
   * https://stackoverflow.com/questions/55587083/ag-grid-sizecolumnstofit-only-when-there-is-space-available-in-the-total-grid-wi#answer-60753786
   */
  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()
      }
    }
  }

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>

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