Ag Grid Call a function on click of checkbox

user11194948 picture user11194948 · May 10, 2019 · Viewed 9k times · Source

In Angular & Javascript, I have Ag-Grid with checkboxSelection: true in one of the column.

I need to call a function whenever the checkbox is clicked for any row... How to do that ?? Once more How to call a function whenever the checkbox is selected in Ag-Grid?

Answer

wentjun picture wentjun · May 10, 2019

I am assuming that only one of the columns has the checkbox selection.

You can make use of the selectionChanged event binding. This event will be emitted whenever you select or deselect the checkbox. You may read up more about it over here.

However, if you want to check if the selected row is checked or unchecked, it will be better to bind to rowSelected event instead.

On the component.html, for instance, you can bind a method, onSelectionChanged() to the selectionChanged event.

<ag-grid-angular
    #agGrid
    style="width: 100%; height: 100%;"
    id="myGrid"
    class="ag-theme-balham"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [suppressRowClickSelection]="true"
    [rowSelection]="rowSelection"
    [rowData]="rowData"
    (gridReady)="onGridReady($event)"
    (rowSelected)="onRowSelected($event)"
    (selectionChanged)="onSelectionChanged($event)"
  ></ag-grid-angular>

And on your component.ts, you will define the onSelectionChanged() method

onRowSelected(event) {
  console.log(event);
  console.log(event.node.selected);
  console.log(event.rowIndex);
}

onSelectionChanged(event) {
  console.log(event); // verify that the method is fired upon selection
  // do the rest
}

Here's a demo.