Search code examples
ag-gridag-grid-angular

Ag-grid "Size to Fit" on desktop and "Auto-Size" on mobile


I need ag-grid to be responsive on all devices. When I tried this.gridApi.sizeColumnsToFit() It looks nice on desktop, but in mobile screen column width gets zero as shown in this image.

When I give this.gridColumnApi.autoSizeColumns(allColumnIds, false); it leaves a blank space if there are less number of columns like shown in this image.

Is there a way to autoFit in desktop and autoSize in smaller screens?


Solution

  • you can call them after another. I'd suggest to first call the autoSizeColumns.

    Afterwards you calculate the actual tableWidth with something like

    const tableWidth = grid.columnApi.getAllColumns()
        .reduce((i, current) => i += current.getActualWidth(), 0);
    

    and then you calculate the actual container width

    const {left, right} = grid.api.getHorizontalPixelRange();
    const containerWidth = right - left;
    

    and only if the tableWidth is smaller than the container width you call `sizeColumnsToFit``

    if (tableWidth < containerWidth) {
         grid.api.sizeColumnsToFit();
    }