Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ag grid sizeColumnsToFit only when there is space available in the total grid width

Is there some function available to adjust the column width to fit the entire grid (basically call the following

api.sizeColumnsToFit()

only when there are not enough headers to fill in the empty space available in the total width.enter image description here

like image 1000
Riya Avatar asked Dec 29 '25 09:12

Riya


1 Answers

i know its a bit late, but you know... better too late than never ;-)

  /**
   * 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();
        }
      }
    }
  }

You can use this method to conditionally resize the columns of the grid. Use resizeColumnsToFit(false) if you don't want to resize the columns when there is a horizontal scroll bar.

Credit: https://github.com/ag-grid/ag-grid/issues/1772

like image 163
Sebastian Avatar answered Dec 30 '25 23:12

Sebastian