- 首先,我们需要创建一个相应的工具栏按钮,并为其定义一个函数和事件监听器。以下是示例代码:
function onToolbarButtonClick(){
var selectedRows = gridOptions.api.getSelectedRows();
// code to handle selected rows
}
var toolbarButton = document.createElement('button');
toolbarButton.innerHTML = 'Drag and Drop';
toolbarButton.addEventListener('click', onToolbarButtonClick);
var toolbarDiv = document.querySelector('#toolbar');
toolbarDiv.appendChild(toolbarButton);
- 然后,我们需要为 Ag-grid 添加 dnd 监听器,并处理从工具栏拖放到网格的逻辑。以下是示例代码:
// define drop zone
var dropZoneParams = {
getContainer: function(){
return gridOptions.api.getDropTarget();
},
onDragEnter: function(e){
// code to handle drag entering grid
},
onDragLeave: function(e){
// code to handle drag leaving grid
},
onDrop: function(e){
var node = e.dragData.node;
if(!node){
return;
}
var data = node.data;
gridOptions.api.updateRowData({add: [data]});
}
};
// add toolbar button dnd
var toolbarButtonDragListener = {
onDragStart: function(e){
var selectedNodes = gridOptions.api.getSelectedNodes();
if(!selectedNodes || !selectedNodes.length){
return null;
}
var selectedData = selectedNodes.map(function(node){ return node.data; });
return {
eventData: selectedData,
draggedNodes: selectedNodes,
node: selectedNodes[0]
};
},
onDragEnd: function(e){
// code to handle dnd ending
}
};
// add dnd to grid
var gridDragAndDrop = {
onGridReady: function(params){
var gridApi = params.api;
var dropZone = gridOptions.api.getDropTarget();
gridApi.addCellDropZone(dropZoneParams);
gridApi.addRowDropZone(dropZoneParams);
}
};
// initialize grid options
var gridOptions = {
// your grid options
onGridReady: gridDragAndDrop.onGridReady,
getDropTarget: function(){
return document.querySelector('#grid-wrapper');
},
rowDragManaged: true,
allowContextMenuWithControlKey: true,
rowSelection: 'multiple',
columnDefs: [
{headerName: 'Column 1', field: 'col_1'},
{headerName: 'Column 2', field: 'col_2'},
{headerName: 'Column 3', field: