kashif
kashif

Reputation: 1147

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

Upvotes: 2

Views: 4373

Answers (1)

msfoster
msfoster

Reputation: 2572

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

Upvotes: 2

Related Questions