Mila
Mila

Reputation: 83

(Ag-Grid) While editing, how to get value changed immediately, not after cell loses focus?

In ag-grid, while entering some values in table, I need to receive updated values on input or change event.

But onCellValueChanged is triggered only when cell loses focus, and I cannot figure out what is the way to get values immediately. The only restriction I have - I can't add custom cellEditor, it needs to be grid default.

Can someone, please, advise how to reach such behavior?

Upvotes: 8

Views: 7616

Answers (3)

Gaurav Mithas
Gaurav Mithas

Reputation: 75

the use case is that you need latest value which is only updated when you blur or hit enter. Assuming, user clicks a cta without blur, we can stop editing inside the cta itself, this internally fires blur and gives latest value.

const handleNextClick = (e) => {
    console.log('handleNextClick', gridRef)
    if (gridRef.current) {
      gridRef.current.api.stopEditing() // This stops any editing mode
    }
    const rowsToDisplay = gridRef?.current?.api.getRenderedNodes()?.map((node) => node?.data)
    console.log(rowsToDisplay, 'rowsToDisplay2')
  }

Upvotes: 0

Shuheb
Shuheb

Reputation: 2352

You can get the current value of the cell whilst editing by leveraging the Grid Event onCellKeyDown:

https://www.ag-grid.com/javascript-grid/keyboard-navigation/#keyboard-events

var gridOptions = {
    onCellKeyDown: params => {
        console.log('current value', params.event.target.value)
    },
}

Please see this sample which showcases this: https://plnkr.co/edit/GbMglD1fxTTeSZFj

Upvotes: 3

Omri Attiya
Omri Attiya

Reputation: 4037

According to ag-grid you can use a custom callback onCellEditingStopped.

This will trigger every time a cell editing is ended.

You define it directly on the grid options object and you can also access the edited values (and its row and column) like this:

const gridOptions = {
  columnDefs: [/* whatever */],
  defaultColDef: {/* whatever */},
  rowData: rowData,
  onCellEditingStopped: function(event) {
    console.log(event);
    console.log(event.oldValue); // cell's previous value
    console.log(event.newValue); // cell's new value
    console.log(event.column); // the column that was edited
    console.log(event.data); // the row that was edited
  },
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
  var gridDiv = document.querySelector('#myGrid');
  new agGrid.Grid(gridDiv, gridOptions);
});

Here you have a detailed explanation of whenever this onCellEditingStopped is triggered.

You can also inspect the full example.

Upvotes: 3

Related Questions