0

The Problem

I am unable to get columns to expand to the size of their content on grid render.

Per the example in the official documentation, and as referenced here, I have tried all three major methods to accomplish this:

  • api.sizeColumnsToFit()
  • columnApi.autoSizeColumns([columnIds])
  • columnApi.autoSizeAllColumns()

I've attempted to get each option working in both onGridReady & onFirstDataRendered (recommended here), and with the column widths defined as flex and then as width. Nothing works.

The Code

I first collect columns from here:

export const configMsDetailsData = function (msDetails: MilestoneDetails) {
  let msRowData: any = [];
  let msColDefs = [
    {
      field: genericRowHeaderTitle,
      cellStyle: genericRowHeaderStyle,
      headerClass: transparentHeaderClass,
      cellClassRules: subMSGrayTextRule,
      resizable: false,
      flex: 1,
      suppressMovable: true,
      pinned: "left",

    },
    {
      field: "Forecast",
      headerClass: blueHeaderClass,
      flex: 1,
      resizable: false,
      valueFormatter: dateFormatter,
      valueGetter: BasicValGetter,
      cellClassRules: grayCellRule,

    },
...

I then create my gridOptions (note: I am including all three suggested options in the code block for demo purposes only. In the actual code, I try one at a time):

let gridOptions = {
    onRowDataUpdated: () => {
      if (!ready) {
        setReady(true);
      }
    },
    onGridReady: (event: any) => {
      event.api.sizeColumnsToFit() //auto-size columns to fit grid
      event.columnApi.autoSizeAllColumns(); //auto-size columns to fit grid

      let allColIds = event.columnApi.getAllColumns().map((col: any) => col.colId);
      event.columnApi.autoSizeColumns(allColIds);
    },
    onFirstDataRendered: (event: any) => {
      event.api.sizeColumnsToFit() //auto-size columns to fit grid
      event.columnApi.autoSizeAllColumns(); //auto-size columns to fit grid
      let allColIds = event.columnApi.getAllColumns().map((col: any) => col.colId);
      event.columnApi.autoSizeColumns(allColIds);

    }
  };

Next, I pass the options to my grid:

const msDeetsGrid = getGrid(
    msDetailsData,
    msDetailsCols,
    defaultColDefMSDeets,
    gridOptions
  );

function getGrid(
  rowData: any,
  colDefs: any,
  defaultColDef: ColDef<any>,
  gridOptions?: any
) {
  return (
    <div className="ag-theme-alpine" style={{ height: "100%", width: "100%" }}>
      <AgGridReact<any>
        gridOptions={gridOptions}
        rowData={rowData}
        columnDefs={colDefs}
        headerHeight={defaultHeaderHeight}
        rowSelection={"single"}
        domLayout={"autoHeight"}
        rowHeight={defaultRowHeight}
        tooltipShowDelay={0}
        tooltipHideDelay={20000}
        defaultColDef={defaultColDef}
      ></AgGridReact>
    </div>
  );
}

Then I render.

Both onGridReady & onFirstDataRendered fire, so I know that's working. But no matter which of the options I use to expand the columns, nothing happens.

Other attempts I've tried:

user
  • 1,261
  • 2
  • 21
  • 43

3 Answers3

1

If you want to use one of the tree sizing methods, you will need to remove the flex properties from the column definitions.

If you have

flex: 1

defined on a column definition, it will ignore calls like

api.sizeColumnsToFit()

You can also mix regular columns and flex cloumns.

https://www.ag-grid.com/angular-data-grid/column-sizing/#column-flex

The flex config does not work with a width config in the same column.

Alexander Zbinden
  • 2,315
  • 1
  • 17
  • 21
  • This worked! Do you have a URL that we could include in the answer that explains this? I didn't realize this would happen. – user Aug 16 '23 at 18:07
0

Note: Below is a general advice that worked for me a number of times. Sharing it since it is somewhat hard to guess given your situation.

To get out from the rabbit hole you seem to have fallen into, do this:

  1. Copy the example that you linked - https://www.ag-grid.com/react-data-grid/column-sizing/#resizing-example (fully, no modifications)
  2. Inject it wherever you test things in your app.
  3. Verify it works as in the link
  4. Replace the code in the example slowly, step by step, until you reach what you wanted to have with the grid. Start with:
...
const onGridReady = useCallback((params) => {
    fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
      .then((resp) => resp.json())
      .then((data) => setRowData(data));
  }, []); 
...

Instead of fetching data, just use setRowData(...) with some random data.

...
const onGridReady = useCallback((params) => {
   setRowData({...})
})

To go slowly do not even change the number of columns (headers) or anything else from the example. Just inject some data of yours to match the example.

Verify resizing works. Then change header keys (keeping widths and everything else). Verify, ... (keep going until resizing is not working anymore or you just made your page works as expected)

The point of all of this is, again, to get out of rabbit hole and see where it breaks for you.

If I needed to make a wild guess of what is going wrong - it would be - missing width in your msColDefs, or that allColIds does not contain proper ids, or something related to wiring everything together...

Good luck!

draganstankovic
  • 5,382
  • 1
  • 27
  • 33
0

Please define a method like that

const autoSizeAll = useCallback(() => {
  const allColumnIds = [];
  gridRef.current.columnApi.getColumns().forEach((column) => {
    allColumnIds.push(column.colId);
  });
    
  gridRef.current.columnApi.autoSizeColumns(allColumnIds);
}, []);

Pass gridRef as a prop to your AgGridReact component

ref={gridRef}

Add a useEffect hook like below

useEffect(() => {
  if (rowData && rowData.length > 0) {
    setTimeout(() => autosizeAll(), 250)
  }
}, [rowData, autoSizeAll])

All In Your getGrid Function

Ahmet Firat Keler
  • 2,603
  • 2
  • 11
  • 22