Search code examples
ag-gridag-grid-angularag-grid-react

Create a button that lowers or increases the column width in ag-grid


I am trying to create two buttons one that increases the column width in ag-grid and another button that decreases the column width when clicked.


Solution

  • You can get access to the latest column width using ColumnApi.getColumnState() and update any columns width using ColumnApi.setColumnWidth(). Here is an example

    const changeWidth = (colId, offset) => () => {
      const currentWitdth = columnApi
        .getColumnState()
        .find((c) => c.colId === colId).width;
      columnApi.setColumnWidth(colId, currentWitdth + offset);
    };
    

    If you want to change the width of all columns

    const changeAllWidth = (offset) => () => {
      const columnState = columnApi.getColumnState();
    
      columnState.forEach((c) => {
        if (c.width) {
          columnApi.setColumnWidth(c.colId, c.width + offset);
        }
      });
    };
    

    Usage

    <button onClick={changeAllWidth(10)}>+ All</button>
    <button onClick={changeAllWidth(-10)}>- All</button>
    
    <button onClick={changeWidth("athlete", 10)}>+ athlete</button>
    <button onClick={changeWidth("athlete", -10)}>- athlete</button>
    <button onClick={changeWidth("age", 10)}>+ age</button>
    <button onClick={changeWidth("age", -10)}>- age</button>
    

    Live Demo

    Edit AgGrid Update Column Width