Search code examples
javascriptag-gridag-grid-angularag-grid-reactag-grid-validation

Ag-Grid: adjust columns width and show horizontal scroll bar once columns reach beyond container size


I've columns panel to add/remove columns from the AG-Grid. There are around 50 columns, by default 5 are showing with property api.sizeColumnsToFit(). it works fine but issue comes when User tries to add more columns and columns reaches beyond the space of the container. it tries to fit in the container size and messed up.

if I removed api.sizeColumnsToFit(), once user removes all columns and keep only 2-3 columns, it does fit in the size, But shows blank space in the grid, which doesn't look good.

Any idea how I can conditionally configure ag-grid to work properly in the following way:

if columns_are_less_than_container_size
  api.sizeColumnsToFit()
else
  Do NOT apply sizeColumnsToFit
  rather show a horizontal scroll

Solution

  • You can implement onDisplayedColumnsChanged and calculate based on the width of the parent element.

    Instead of getActualWidth you might want to define a minimum width and use getMinWidth.

    onDisplayedColumnsChanged(params) {
        const gridWidth = document.getElementById("parent").offsetWidth;
        const widthVisibleColumns = params.columnApi.getAllColumns()
          .filter(c => c.isVisible())
          .map(c => c.getActualWidth())
          .reduce((a, b) => a + b);
        if (gridWidth > widthVisibleColumns) {
          params.api.sizeColumnsToFit();
        }
    }