Search code examples
angularag-gridag-grid-angular

ag-grid: Get sorted selected rows


I have an ag-grid with filtering and sorting and have enabled multiple row selection. The documentation provides a method (getSelectedRows()) to get the selected rows but only unsorted. Is there another way to get the rows with the current sorting, without having to sort the data again?

// template

  <ag-grid-angular
    class="ag-theme-alpine data-grid" 
    [getRowId]="getRowId"
    [columnDefs]="columnDefs"
    [columnTypes]="columnTypes"
    [defaultColDef]="defaultColDef"
    [rowModelType]="rowModelType"
    [serverSideInfiniteScroll]="true"
    [pagination]="true"
    [paginationPageSize]="paginationPageSize"
    [cacheBlockSize]="cacheBlockSize"
    [maxBlocksInCache]="maxBlocksInCache"
    [editType]="editType"
    [rowSelection]="'multiple'"
    (selectionChanged)="onSelectionChanged()"
    (gridReady)="onGridReady($event)"
    (modelUpdated)="onModelUpdated($event)"
    (rowValueChanged)="onRowValueChanged($event)"
  ></ag-grid-angular>

// typescript

  onSelectionChanged() {
    console.log("selected", this.gridApi.getSelectedRows()); // this prints the unsorted data, even when sorting is applied
  }


Solution

  • I solved it like this:

    onSelectionChanged() {
      const selectedRows = this.gridApi.getSelectedNodes();
      const selectedSortedRows: any[] = [];
      this.gridApi.forEachNode((node, index) => {
        const row = selectedRows.find(row => row.id == node.id)?.data;
        if(row){
          selectedSortedRows.push(row);
        }
      })
      console.log(selectedSortedRows);
    }
    

    This is not perfect because of the nested loops, I'll leave it here until a better answer is posted