Search code examples
javascriptangulargridag-gridag-grid-angular

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?


Solution

  • 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.