Search code examples
reactjsag-gridag-grid-react

How can I edit newly added pinned rows?


I'm having some issues with ag-grid. I want to click an add row button and add a new row to the top of my grid. To accomplish this I think I need to make use of a temporary pinned row so the item always shows at the top no matter what sorting has been enabled. As soon as the pinned row is added I also want to start editing the row. This is how I'm trying to accomplish this right now, but its not working. If I put a delay in after setting the pinned top row data it works. There has to be a better way to accomplish this.

const addRow = () => {
    gridApi.setPinnedTopRowData([myNewItem]);
    gridApi.startEditingCell({
      rowIndex: 0,
      rowPinned: 'top',
      colKey: 'myColumnKey',
    });
}

Solution

  • I have a better alternative for you.

    In this example, we have a pinned row at the top of the grid. We double click each cell, enter values until the last column and press enter. Voila! A new row has been added to the top!

    Beginning

    Beginning

    Entering Values

    Entering Values

    Final State

    Final State

    To achieve that, refer to this blog: https://blog.ag-grid.com/add-new-rows-using-a-pinned-row-at-the-top-of-the-grid/

    or refer to my Stackblitz link: https://stackblitz.com/edit/js-pinned-input-row-blog-fzknf4?file=index.js

    I have made a minor change in the code of the blog because you wanted the new row to be on top

    onCellEditingStopped: (params) => {
      if (isPinnedRowDataCompleted(params)) {
        // save data
        setRowData([inputRow, ...rowData]); // minor change
        //reset pinned row
        setInputRow({});
      }
    },
    

    UPDATE

    If you want to perform some actions right after pinning row, I have found a grid event: onPinnedRowDataChanged

    Let's give this a try

    onPinnedRowDataChanged: (params) => {
      gridApi.startEditingCell({
        rowIndex: 0,
        rowPinned: 'top',
        colKey: 'myColumnKey',
      });
    },