Search code examples
angulartypescriptag-gridag-grid-angularangular11

Multiple ag-grids - setSelected to true is only working for the last grid


I have a for loop over an array and creating ag-grid based on the content of the array . based on data , I am preselecting the ag-gird rows ,

gridReady method

  onGridReady(event) {
    this.resultsArray.forEach(result => {
      result.gridOption.api = event.api;
      result.gridOption.columnApi = event.columnApi;  
    });
      event.api.forEachNode((node) => {
      if (node.data?.selected) {
        node.setSelected(true);
      }
    });
  }

resultsArray contains the data and gridoptions for each of the grid . suppose a user deselects some rows from both the grids , and then click on reset . it should reset both grids but its only reseting last grid

reset method

  onReset(){
      this.resultsArray.forEach(result => {     
      result.gridOption.api.forEachNode((node) => {
      if (node.data?.selected) {
        node.setSelected(true);
      }
    });
    });
  }

my stackblitz demo https://stackblitz.com/edit/angular-ag-grid-angular-mtpg6q?

any suggestion on how to reset every grid , not the last grid only .


Solution

  • You are overriding the grid API in the onGridReady method. Both 'results' will have the API of the last.

    You have to change:

    Add identifier groupName for the gridReady method to know which API you want to set:

    <!-- src/app/my-grid-application/my-grid-application.component.html -->
    <div>
        <button (click)="onReset()">Reset</button>
    </div>
    
    <div *ngFor="let result of resultsArray; let resultIndex = index">
        <div>{{result.groupName}}</div>
        <ag-grid-angular #agGrid style="width: 80%; height: 80%;" class="ag-theme-fresh" [gridOptions]="result.gridOption"
            [defaultColDef]="defaultColDef" [columnDefs]="myColumnDefs" (gridReady)="onGridReady($event, result.groupName)"
            [rowSelection]="rowSelection" [rowData]="result.data" [rowMultiSelectWithClick]="true">
        </ag-grid-angular>
    </div>
    

    Add the check within an if:

    onGridReady(event, groupName) {
        this.resultsArray.forEach(result => {
          if(result.groupName == groupName) {
            result.gridOption.api = event.api;
            result.gridOption.columnApi = event.columnApi;
            result.gridOption.api.sizeColumnsToFit(); 
          }
        });
          event.api.forEachNode((node) => {
          if (node.data?.selected) {
            node.setSelected(true);
          }
        });
      }
    

    Here is a working stackblitz project.