ag-gridag-grid-angularag-grid-reactag-grid-vue

How can I autosize all the columns in ag-grid when column virtualization is switched on?


According to the ag-grid documentation (https://www.ag-grid.com/javascript-data-grid/column-sizing/)

"The choice is yours, whether you want column virtualisation working OR auto-size working using off-screen columns"

What this means is uf you have many columns that are off-screen, they do not physically exist and so will not be autosized.

Is there any way I can hack around the built-in limitation in the library, so that I can make use of both features?


Solution

  • Here is another (hacky) solution, which needs access to some internal classes of ag-grid. Simply disable columnVirtualisation while autosize:

    const col: any=gridApi.getColumns()?.[0]
    col.stubContext.beans.colViewport.suppressColumnVirtualisation = true;
    col.stubContext.beans.rowRenderer.redrawRows();
    gridApi.autoSizeColumns(cols, skipHeader);
    col.stubContext.beans.colViewport.suppressColumnVirtualisation = false;
    

    Tested in ag-grid 33