Ag-grid: Count the number of rows for each filter choice

时光怂恿深爱的人放手 提交于 2020-01-04 04:03:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!