Search code examples
javascriptag-gridag-grid-js

How to dynamically hide/show entire column groups in Ag-grid community?


I would like to mimic a simple form of the side bar of Ag-grid-enterprise: collect (using JavaScript) all column groups in a grid, and for each of them set a checkbox to show or hide the whole group.

I know I can hide columns with gridApi.setColumnsVisible(['col1','col2'], false), as explained in this question. However, I'd like to hide entire column groups at once. Is there a simple way to do this instead of hiding the columns "by hand"?

If I have to do it per column, is there a simple way to get the columns in a given column group?


Solution

  • you can use the getColumnGroup by passing in the groupId. This will give the group of interest.

    function setColumnsVisible(
        keys: (string | Column)[],
        visible: boolean
    ): void;
    

    setColumnsVisible accepts an array of string or array of Column

    Now you can use 2 options. First is to map through the children and create an array of col names and then pass in to the set. This uses the string[] approach.

    const cols = gridApi.getColumnGroup('ColGroup').getChildren().map((column) => column.colId)
    gridApi.setColumnsVisible(cols, false)
    

    or there is getLeafColumns which gives an array of Column instances. You can use with the Column[] approach

    setColumnsVisible(gridApi.getColumnGroup('ColGroup').getLeafColumns(), false)