4

While selecting the rows of an ag-grid with the help of cell selection using : this.gridOptions.rowMultiSelectWithClick = true ; Is it possible to access the last selected row only for computation and keep the previously selected rows state intact.

Alf Moh
  • 7,159
  • 5
  • 41
  • 50
nikom
  • 71
  • 1
  • 1
  • 10
  • How do you know when will be your last selection, because when `this.gridOptions.rowMultiSelectWithClick = true` you can click and select any number of times. – Senal May 17 '18 at 05:23
  • With the help of getSelectedRows() it will have the instance of the rows selected and will keep all the rows information, I want to access the instance of the latest selected row and needs to do the computation and hence there is a requirement for the mechanism to access the last row using getSelectedRows, keeping the rest rows state intact. – nikom May 17 '18 at 10:08

2 Answers2

4

Adding to what Paritosh mentioned, you could listen to rowSelected event and maintain an array of nodes.

<ag-grid-angular
   [rowSelection]="rowSelection"
   (rowSelected)="onRowSelected($event)"
   [rowMultiSelectWithClick]="true"
   (selectionChanged)="onSelectionChanged($event)"></ag-grid-angular>
selectedNodes: RowNode[];     

onRowSelected(event) {
   if(event.node.selected) {
      this.selectedNodes.push(event.node);
   }
}

getLastItem() {
   return this.selectedNodes[this.selectedNodes.length - 1];
} 

You can call getLastItem() method any time according to your requirement and get the lastly selected node.

Senal
  • 1,510
  • 1
  • 14
  • 22
  • 1
    you also need to take care of the scenario and make sure that the node is removed if a node is deselected. so this solution is not yet perfect. Also, we also have `api.getSelectedNodes()` and `api.getSelectedRows()` in `gridApi`. better to use those api to achieve this - as updated in my answer. – Paritosh May 18 '18 at 04:53
3

Sure, you have to use onRowSelected event for that, in which you'll get the required data as event argument.

onRowSelected(event) {
  console.log("row " + event.node.data + " selected = " + event.node.selected);
}

The data: event.node.data
Selected or not: event.node.selected

<ag-grid-angular
  .....
  [rowSelection]="rowSelection"
  (rowSelected)="onRowSelected($event)"
  [rowMultiSelectWithClick]="true"
  (selectionChanged)="onSelectionChanged($event)"
  ></ag-grid-angular>

Here is the live example: Plunk - ag-grid rowMultiSelectWithClick


Update

You can use gridApi to then get the last selected node. This will even work when you are deselecting a row. It would give us the last row which was selected before deselecting the latest row.

getLastSelectedNode(){
  let rows = this.gridApi.getSelectedRows();
  if(rows.length > 0)
    console.log(rows[rows.length - 1]);
  else
    console.log('No rows selected');
}

Updated Plunk

Paritosh
  • 11,144
  • 5
  • 56
  • 74