Search code examples
angular8ag-grid-angular

ag-grid angualr i want duplicate the selected row data inside same grid i.e i want copy and pate selected row on button click in the same grid


In Ag-grid angular,i have button clone row, i will select a row inside grid and click on clone row it should create same row once again in specified index,i was able to achieve this using following code

in app.ts::

clone Row(){

var selectedRowsIndex = this.gridOptions.api.getSelectedNodes();

     var index = selectedRowsIndex[0].rowIndex
var selectedRows = this.gridOptions.api.getSelectedRows();
const temp =  [...selectedRows] 
for (var i = 0; i < selectedRows.length; i++) {
  temp[i].B_CLONE = true;
  temp[i].SNO = 3;

}
this.gridOptions.api.insertItemsAtIndex(++index,temp)

}

<button class="btn btn-info ml-3" (click)="cloneRow()">Clone Row</button>

<button class="btn btn-info ml-3" (click)="cloneRow()">Clone Row</button>

Issue i am facing was, after cloning a row(insertItemsAtIndex)

  1. existing row also being changed with new clone row if add any value i.e s.no in gird

  2. if i edit any of 2 rows duplicated and change any value in any one cell of row getting changed n both the rows are changed.

i want to two rows independent of their values

i am attaching screen short for easy understanding.

original grid before clone

grid after clone

grid after clone changing cell value in one row


Solution

  • You need to deep clone and assign the the temp object like this:

    this.gridOptions.api.insertItemsAtIndex(++index,Object.assign({}, temp));
    

    Instead Object.assign({}, temp) you can also clone the object like this (the old school way of cloning):

    this.gridOptions.api.insertItemsAtIndex(++index,JSON.parse(JSON.stringify(temp)));