Niklas
Niklas

Reputation: 13135

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.
}

Upvotes: 4

Views: 7706

Answers (1)

thirtydot
thirtydot

Reputation: 228162

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);
}

Upvotes: 5

Related Questions