Search code examples
angularag-grid

Count number of selected rows in ag-grid


I want to count the number of selected rows but it seems onRowClicked or onRowSelected happens before the row i click actually is selected.

How can I count the number of rows when I select a row? I thought this was the way to go.

this.gridOptions.onRowSelected = function (params) {
    console.log(this.gridOptions.api.getSelectedRows().length) 
    // Prints one less then the number of rows that is selected.
}

Solution

  • In a React (with ES6) project I use this:

    onSelectionChanged = debounce((e) => {
        this.setState({
            selectedRows: this.api.getSelectedRows(),
        });
    }, 1)
    

    (this.api is https://www.ag-grid.com/javascript-grid-api/?framework=all#gsc.tab=0)

    I use Lodash's debounce to solve a performance problem if many rows are selected at the same time. (Although after some quick testing, looks like this has been fixed in ag-grid at some point.)

    The simplest version could look like (untested):

    this.gridOptions.onSelectionChanged = function () {
        console.log(this.gridOptions.api.getSelectedRows().length);
    }