Akshay Krishna
Akshay Krishna

Reputation: 163

How to add new row to a particular index of a ag grid using angular 7

I am trying to add a new row into a particular index of a ag-grid but i am unable to add it. when i try to add it's adding entire things in grid again and creating duplicate along with the new row. Please help me on this.

I am getting the index of the selected row and i want to add new row just below the selected row.

Code for getting index of a selected row.

  onRowClick(event: any): void  {
    this.index = event.rowIndex;
  }

and i am calling this in angular-ag-grid as below:

   (rowClicked)="onRowClick($event)"

And for adding row below is my try:

 addRow(){
  this.lst.push( {"slNo": this.index,"id":3, "rank":1,
  this.gridApi.updateRowData({
  add: this.lst,
  addIndex: index
  });
}

Here lst is the object model which contain all rows in the arraylist format and i am pushing new row to that array. And index i am getting from the onRowClick event.

When i try in above method it's duplicating the value those already present in the array along with the new row.

Please help me !

Upvotes: 1

Views: 8270

Answers (2)

omostan
omostan

Reputation: 881

Another solution is to use javascript with splice like: arr.splice(targetIndex, 0, newRow).

change your method to this:

addRow(){
  // Assuming newRow is an object, such as {"slNo": this.index,"id":3, "rank":1};
  rowData.splice(targetIndex, 0, newRow);
  this.gridApi.setRowData(rowData); // optional
}

Array.splice() method is used to add or remove items from an array. In the case above, the insertion is done by setting the number of elements to be deleted to 0. The "newRow" will be inserted at the specified index (0) for the first row. You can also for example set the index = 1 for the second row. Optionally use "setRowData(rowData)" method from the API to re-render the view.

Upvotes: 0

wentjun
wentjun

Reputation: 42526

The actual usage of api.updateRowData(transaction) only requires you to pass the particular row you are trying to add into the parameter. Therefore, you shouldn't be passing in the entire lst object, as this will cause the entire object to be duplicated within your ag-grid.

This is what you should be doing instead:

addRow(){
  // Assuming newRow is an object, such as {"slNo": this.index,"id":3, "rank":1}
  this.gridApi.updateRowData({
    add: newRow,
    addIndex: index
  });
}

The official documentation has a decent selection of examples for you to refer to.

Upvotes: 3

Related Questions