如何在AG Grid中点击按钮克隆行节点并保留原数据且支持编辑
Hey there! Let me walk you through a solid approach to build row cloning in AG Grid that meets your needs—cloned rows will have exact copies of the original row's data, and you'll be able to edit them independently later.
Core Idea
The key here is to create a deep copy of the target row (so changes to the clone don't affect the original), add this copy to your grid's data source, and ensure the clone has a unique identifier (if your grid uses row IDs). This way, AG Grid treats the clone as a separate, editable row.
Step-by-Step Implementation
1. Grab the Selected Row First
First, use AG Grid's API to get the row the user wants to clone. I'll assume single selection here, but we'll touch on multi-selection later:
// Get the first selected row (adjust if using multi-select) const selectedRow = gridApi.getSelectedRows()[0]; if (!selectedRow) { alert("Pick a row to clone first!"); return; }
2. Deep Copy the Row Data
Don't use shallow copies like Object.assign() or the spread operator (...)—they'll let the original and cloned row share nested data (like objects or arrays), leading to unexpected linked edits. Instead:
// Option 1: Use native structuredClone (modern browsers, no dependencies) const clonedRow = structuredClone(selectedRow); // Option 2: For older browser support, use Lodash's cloneDeep // const clonedRow = _.cloneDeep(selectedRow);
3. Assign a Unique ID (Critical!)
If your grid uses a unique row ID (via the getRowId callback or id field in your data), you must generate a new unique ID for the clone. Without this, AG Grid will treat the clone as the same row as the original, breaking editing and grid behavior:
// Example: Generate a unique ID using timestamp + random string clonedRow.id = `clone-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
4. Add the Clone to Your Data Source & Refresh the Grid
Now add the cloned row to your data set and tell AG Grid to update. Using updateRowData is more efficient than resetting the entire data set:
// Add the cloned row to the grid gridApi.updateRowData({ add: [clonedRow] }); // Optional: Auto-select the new cloned row for convenience gridApi.selectNode(clonedRow);
5. Ensure Clones Are Editable
As long as your column definitions have editable: true set, cloned rows will be editable just like the original. Here's a quick example of editable column config:
const columnDefs = [ { field: 'id', headerName: 'ID', editable: false }, // Lock ID to prevent edits { field: 'productName', headerName: 'Product', editable: true }, { field: 'price', headerName: 'Price', editable: true }, // Add other columns as needed ];
Full Working Example
Here's a complete function you can drop into your code:
function cloneSelectedRow() { const selectedRow = gridApi.getSelectedRows()[0]; if (!selectedRow) { alert("Please select a row to clone."); return; } // Deep copy the row data const clonedRow = structuredClone(selectedRow); // Generate a unique identifier clonedRow.id = `clone-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; // Add clone to grid and auto-select it gridApi.updateRowData({ add: [clonedRow] }); gridApi.selectNode(clonedRow); }
Quick Notes for Edge Cases
- Multi-selection: To clone multiple rows, loop over
gridApi.getSelectedRows(), clone each one, and pass all clones toupdateRowData({ add: clonedRowsArray }). - Special data types: If your rows have Date objects or custom classes,
structuredCloneworks for most cases, but you may need to manually copy these fields if you hit edge cases. - Framework integrations (React/Vue/Angular): If you're using AG Grid with a framework, just update your component's data state (e.g., React's
setRowDatastate) instead of callinggridApi.updateRowData—the framework will handle the grid refresh automatically.
内容的提问来源于stack exchange,提问作者Deepender Sharma

