Programmatically select a row ag-grid + angular 2

Astraea picture Astraea · Aug 15, 2017 · Viewed 17.3k times · Source

Trying to select first row by default in ag-grid. As per ag-grid documents, I should be able to do this using NodeSelection Api(https://www.ag-grid.com/javascript-grid-selection/?framework=all#gsc.tab=0). But I am not able to get to node object at all. HTML file

<div class="pulldown panel panel-default">
          <div class="panel-heading">{{rulesSummaryTitle}}</div>
          <ag-grid-angular #agGrid   class="ag-fresh ag-bootstrap"
                           [gridOptions]="gridOptions"
                           [rowData]="rowData"
                           [columnDefs]="columnDefs"
                           [enableSorting]="true"
                           rowSelection="single"
                           [pagination]="true"
                           [suppressCellSelection]="true"
                           (gridReady)="onGridReady($event)"
                           (rowSelected)="onRowSelect($event)">
          </ag-grid-angular>
      </div>

I am calling node selection api in "onGridReady" method but errors out with error message "cant call setSelected on undefined".

public onGridReady(event: any): void {
    event.api.sizeColumnsToFit();
    this.gridOptions.api.node.setSelected(true);
  }

Answer

Jarod Moser picture Jarod Moser · Aug 15, 2017

There isn't a node attribute on the gridOptions.api object. You will want to do something more like this:

public onGridReady(event: any): void {
    event.api.sizeColumnsToFit();
    gridOptions.api.forEachNode(node=> node.rowIndex ? 0 : node.setSelected(true))
  }

This will check over each node in the data and see if the rowIndex is 0, when it is, it uses the node object to set the selected attribute