This post will show how to delete selected rows and cell ranges in ag-Grid by pressing the Backspace or Delete keys. This will allow your end-users to easily edit data in ag-Grid using the keyboard.

We have demonstrated this in live samples in JavaScript, Angular, React and Vue.js.

Please see the illustration below demonstrating this:

See the live sample in JavaScript below and links to the same sample in other frameworks just below it. In this demo, please select rows/cells and press the Delete key to delete the selected range, and the Backspace key to delete selected rows.

Live examples

Open the live example in all the major frameworks using the links below:
 •  JavaScript (using Transaction updates)
 •  JavaScript (using Immutable Data)
 •  Angular (using Immutable Data)
 •  React (using Immutable Data)
 •  Vue (using Immutable Data)

Contents

Overriding default key press behavior

ag-Grid already implements a default behavior when the Delete key is pressed - it starts editing the focused cell and clears its value as shown below:

In order to override this default behavior and implement a different behavior for pressing Delete, we need to define a suppressKeyboardEvent callback in our default column definition.

This callback receives a params object that holds the keyPress event, the grids API and other useful parameters. Returning true in the callback tells the grid to suppress the event, thus removing the default behavior for the Delete key.

See this implemented below in the code below:

defaultColDef: {
    suppressKeyboardEvent: params => {
        if (!params.editing) {
            let isBackspaceKey = params.event.keyCode === 8;
            let isDeleteKey = params.event.keyCode === 46;
			
            if (isBackspaceKey) {
                // Delete all selected rows...
				return true
			}
			
			if(isDeleteKey){
                // Delete all selected cell ranges...
                return true
			}
        }
        return false;
    }
}

In the code above, note that we are only applying this behavior to these key presses when the user isn't already editing the cell.

If you'd like to implement additional custom behaviors on key press, you can learn more about the Suppress Keyboard Event approach in our documentation.

Deleting Selected Rows

Now that you can set your own custom behavior for key press via suppressKeyboardEvents let's add logic to delete rows when the Backspace key is pressed. We will be calling our row deletion logic inside the first if statement below:

    if (isBackspaceKey) {
          const selectedRows = params.api.getSelectedRows();
          params.api.applyTransaction({ remove: selectedRows });
          return true;
    }

As you can see in the code above, if the user has pressed the Backspace key, we get the selected rows via the grid API and pass them to our transaction update to delete them. You can learn more about these topics in the documentation on Transaction Updates and Row Selection.

Deleting Selected Cell Ranges

Let's now use the same approach to implement deleting the values in the selected cell ranges. This way when the user selects a cell range and presses the Delete key, we will update the underlying cell data to an empty string.

First, we will need to retrieve the rows that are included in the cell range selection and the columns we need to update in those rows.

Since there can be more than one selected cell range, we will need to execute the cell deletion logic for each of the separate range selections.

Please see the code below getting the cell ranges and deleting their values:

if (isDeleteKey) {
    // for each of our range selection
    params.api.getCellRanges().forEach(range => {
        let colIds = range.columns.map(col => col.colId);

        let startRowIndex = Math.min(
            range.startRow.rowIndex,
            range.endRow.rowIndex
        );
        let endRowIndex = Math.max(
            range.startRow.rowIndex,
            range.endRow.rowIndex
        );

        clearCells(startRowIndex, endRowIndex, colIds, params.api);
    });
}

Notice that we are getting all the Range Selections via the ag-Grid's API. The range selection object holds which columns are in the range selection and the startIndex and the endIndex of the selected range.

We start by mapping columns in the selected range to column ids. This will tell us which columns (fields) we will need to update in the rows.

We then assign the lowest row index to the startRowIndex and the biggest row index to the endRowIndex. This is to handle cases where the user selected a range from bottom to top, resulting in the start index being bigger than the end index.

Now that we know the row indexes and the columns that we need to update, we call the clearCells function to get the rows between the start and end index and update the column fields for the cells selected as shown below:

function clearCells(start, end, columns, gridApi) {
  let itemsToUpdate = [];

  for (let i = start; i <= end; i++) {
    let data = gridApi.rowModel.rowsToDisplay[i].data;
    columns.forEach(column => {
      data[column] = "";
    });
    itemsToUpdate.push(data);
  }

  gridApi.applyTransaction({ update: itemsToUpdate });
}

As you can see in the code above, we cycle through the rows in the selected cell range by its index using the rowModel.rowsToDisplay array, and update the corresponding fields, saving this with a transaction update.

If you'd like to customize the range selection behavior, you can learn more about that in our documentation.

What's next?

We hope that you find this article useful whenever you're looking to enable users to quickly delete selected rows and cell values. Please use the samples in the blogpost and modify them as you see fit.

If you would like to try out ag-Grid check out our getting started guides (JS / React / Angular / Vue)

Happy coding!