AG Grid is the best JavaScript plugin I've ever worked with (I've been meaning to write about it, and I hope to soon). Oddly, one of the few features it doesn't support out of the box is clipboard support for cutting data with Ctrl + X
. Copy and paste are provided, but cut support is not. Here's how I added support for this operation (we use the Enterprise variant at work, so this code is geared towards that flavor).
let gridOptions = {
// ... other grid options ...
'onCellKeyDown': function(e) {
if(e.event.key == "x" && (e.event.ctrlKey || e.event.metaKey)) {
e.api.copySelectedRangeToClipboard();
e.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, e.api);
});
}
},
};
let div = document.querySelector("#my-grid");
g_MyGrid = new agGrid.Grid(div, gridOptions);
The clearCells
function looks like the following, and handles actually resetting the value of the cell to some default value (I set mine to 0, since I'm working with numerical data):
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] = "0";
});
itemsToUpdate.push(data);
}
gridApi.applyTransaction({update: itemsToUpdate});
}