NicuVlad
NicuVlad

Reputation: 2601

Ag-grid: clear cell when "agSelectCellEditor" is used

As stated in the ag-grid documentation:

The default editor will clear the contents of the cell if Backspace or Delete are pressed.

But this doesn't work when the "agSelectCellEditor" is used. If you press Delete or Backspace the cell will enter in EDIT mode and you can choose only the values that are provided as options.

Any idea how can I achieve the same behavior?

Upvotes: 2

Views: 2606

Answers (2)

Denis Karabaza
Denis Karabaza

Reputation: 1

This was fixed in 28.2.0, now delete key always clears the cell without entering the "editing mode".

Reference: https://github.com/ag-grid/ag-grid/releases/tag/v28.2.0, AG‑4801

Upvotes: 0

NicuVlad
NicuVlad

Reputation: 2601

I found an article that explain how to write the delete cells logic. This works also for multiple cells. Please check this article: https://blog.ag-grid.com/deleting-selected-rows-and-cell-ranges-via-key-press/

Basically you override the default behavior of the DELETE or BACKSPACE keys using suppressKeyboardEvent callback in our default column definition:

defaultColDef: {
    suppressKeyboardEvent: params => {
        if (!params.editing) {
            let isBackspaceKey = params.event.keyCode === 8;
            let isDeleteKey = params.event.keyCode === 46;
            
            if (isBackspaceKey || isDeleteKey) {
              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);
            }
        }
        return false;
    }
}

And the delete method:

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 });
}

This works as expected.

Upvotes: 1

Related Questions