问题
In my ag-grid I want to display counts of rows next to each filter choice in a set filter, and maybe sort choices by that count (descending). This is what it looks like by default:
I want the choices to be displayed as
- Select All (88)
- Katie Taylor (2)
- Darren Sutherland (1)
- John Joe Nevin (1)
- Barack Obama (0)
- ...
What is the most efficient way to get those counts (and maybe sort the choices accordingly) from the row data, taking into account filters already set in the other fields (if any)?
回答1:
Assuming your columns field is "name", you could try building up a map and refer to this in the filters cellRenderer:
var nameValueToCount = {};
function updateNameValueCounts() {
nameValueToCount = {};
gridOptions.api.forEachNodeAfterFilter((node) => {
if(!nameValueToCount.hasOwnProperty(node.data.name)) {
nameValueToCount[node.data.name] = 1;
} else {
nameValueToCount[node.data.name] = nameValueToCount[node.data.name] + 1;
}
});
}
And your column def would look like this:
{
headerName: "Name",
field: "name",
width: 120,
filter: 'set',
filterParams: {
cellRenderer: NameFilterCellRenderer
}
},
And finally, the NameFilterCellRenderer
would look like this:
function NameFilterCellRenderer() {
}
NameFilterCellRenderer.prototype.init = function (params) {
this.value = params.value;
this.eGui = document.createElement('span');
this.eGui.appendChild(document.createTextNode(this.value + " (" + nameValueToCount[params.value] + ")"));
};
NameFilterCellRenderer.prototype.getGui = function () {
return this.eGui;
};
You would need to ensure that you called updateCountryCounts
to update it when data changed (either with new/updated data, or when a filter was updated etc), but this should work for your usecase I think
来源:https://stackoverflow.com/questions/40865679/ag-grid-count-the-number-of-rows-for-each-filter-choice