Sometimes your users want to remove rows and cells in AG Grid by pressing Backspace or Delete keys.
See this implemented in a blogpost with samples in Angular/React/Vue and JavaScript here:
https://blog.ag-grid.com/deleting-selected-rows-and-cell-ranges-via-key-press/
The following example uses api.applyTransaction
({...}) to remove selected rows, when the user presses BACKSPACE or DELETE keys.
See the live example here:
https://plnkr.co/edit/u856TebOHvrdaksE
You can see this illustrated below:
The key to achieving this behaviour is the following function:
function keyDownListener(e) {
// delete the rows
// keyCode 8 is Backspace
// keyCode 46 is Delete
if(e.keyCode === 8 || e.keyCode === 46) {
const sel = gridOptions.api.getSelectedRows();
gridOptions.api.applyTransaction({remove: sel});
}
}
Clearing selected cells when Backspace or Delete is pressed
This example shows how to capture key press events via the grid by leveraging the Grid Event onCellKeyDown.
See the live example here:
https://plnkr.co/edit/NOB8waSBy3sWcbq2?preview
You can also achieve the same functionality shown by the approach shown in the example above using the DOM Event instead.
The key here is to listen to the key presses for delete/backspace and then call api.getCellRanges to know which cells to clear.
To clear the cell, we are calling rowNode.setDataValue, however there are many other ways shown in our documentation
function onCellKeyDown(e) {
let keyPress = e.event.keyCode;
if(keyPress ===8|| keyPress ===46) {
let cellRanges = e.api.getCellRanges();
cellRanges.forEach(cells => {
let colIds = cells.columns.map(col => col.colId);
let startRowIndex =Math.min( cells.startRow.rowIndex, cells.endRow.rowIndex);
let endRowIndex =Math.max(cells.startRow.rowIndex, cells.endRow.rowIndex);
clearCells(startRowIndex, endRowIndex, colIds);
});
}
}
function clearCells(start, end, columns) {
for(let i = start; i <= end; i++) {
let rowNode = gridOptions.api.getRowNode(i);
columns.forEach(column => {
rowNode.setDataValue(column, '');
});
}
Comments
0 comments
Please sign in to leave a comment.