Dash AG Grid columnGroupOpened eventListener

Hello everyone,

I have a question regarding the eventListener function in dash_ag_grid. I am working with a table that features multiple hierarchical column groups, each initialized with either "columnGroupShow": "closed" or "columnGroupShow": "open", so that users can toggle the visibility of the columns. When a user opens or closes a column group, I would like to trigger a callback that indicates which columns (from my columnDefs) are currently visible.

According to the Grid Events Reference (React Grid: Grid Events Reference | AG Grid), the ColumnGroupOpenedEvent should provide the functionality I need. I have also reviewed the examples on Dash AG Grid Event Listeners (v 31.2), but as I am relatively new to Dash, I have not yet been able to implement a similar event listener to capture the column group state.

Any help or guidance would be greatly appreciated. I can provide an example of how the column groups are set up:

import dash
from dash import html, Output, Input, dcc, State
import dash_ag_grid as dag

app = dash.Dash(__name__)

columnDefs = [
    {
        "headerName": "Group A",
        "children": [
            {
                "field": "col1",
                "headerName": "Column 1",
                "columnGroupShow": "closed" # closed if Column 2 is open
            },
            {
                "field": "col2",
                "headerName": "Column 2", # closed if Column 1 is open
                "columnGroupShow": "open"
            }
        ]
    },
    {
        "headerName": "Group B",
        "children": [
            {
                "headerName": "Subgroup B1",
                "children": [
                    {
                        "field": "col3",
                        "headerName": "Column 3",
                        "columnGroupShow": "closed" # closed if Column 4 is open
                    },
                    {
                        "field": "col4",
                        "headerName": "Column 4",
                        "columnGroupShow": "open" # closed if Column 3 is open
                    }
                ]
            },
            {
                "field": "col5",
                "headerName": "Column 5" # always opened
            }
        ]
    }
]

rowData = [
    {"col1": "A1", "col2": "A2", "col3": "B1", "col4": "B2", "col5": "B3"},
    {"col1": "A3", "col2": "A4", "col3": "B4", "col4": "B5", "col5": "B6"},
]

app.layout = html.Div([
    dag.AgGrid(
        id="grid",
        columnDefs=columnDefs,
        rowData=rowData,
    ),
    html.Div(id='output_div', children=[]),
    dcc.Store(id='opened_column_groups', data=[])
])

@app.callback(
    Output('opened_column_groups', 'data'),
    Output('output_div', 'children'),
    Input('output_div', 'children'), # This should be the Event triggered by an opened columnGroup
    State('opened_column_groups', 'data'),
)
def update_column_groups_opened(children, data):
    opened_groups = []

    # get name of opened columns and add them to opened_groups

    return opened_groups, f"Opened Column Groups: {opened_groups}"

if __name__ == '__main__':
    app.run_server(debug=True)

Thank you in advance!

Hi @VanHalbe and welcome to the Dash community :slight_smile:

Try running this example:


import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

app = Dash()

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)

columnDefs = [
    {
        "headerName": "Athlete Details",
        "children": [
            {"field": "athlete", "width": 180},
            {"field": "age", "width": 90},
            {"field": "country", "width": 140},
        ],
    },
    {
        "headerName": "Sports Results",
        "children": [
            {"field": "sport", "width": 140},
            {"field": "total", "width": 100, "filter": "agNumberColumnFilter", "columnGroupShow": "closed"},
            {"field": "gold", "width": 100, "filter": "agNumberColumnFilter", "columnGroupShow": "open"},
            {"field": "silver", "width": 100, "filter": "agNumberColumnFilter", "columnGroupShow": "open"},
            {"field": "bronze", "width": 100, "filter": "agNumberColumnFilter", "columnGroupShow": "open"},
        ],
    },
]

app.layout = html.Div(
    [       
        dag.AgGrid(
            id="grid",
            rowData=df.to_dict("records"),
            columnDefs=columnDefs,
            defaultColDef={"filter": True},
            dashGridOptions={"animateRows": False},        
            eventListeners={'columnGroupOpened': ['myFunction(params, "out")']}
        ),
        html.Div(id="out"),

    ]
)

if __name__ == "__main__":
    app.run(debug=True)

Place the following in the dashAgGridFunctions.js file in the assets folder:

var dagfuncs = (window.dashAgGridFunctions = window.dashAgGridFunctions || {});

dagfuncs.myFunction = (params, id) => {
      console.log(params) // use this to see the data available in the event
      
      const groupColName = params.columnGroups[0].colGroupDef.headerName
      const expandedState = params.columnGroups[0].expanded
      const children =groupColName + " expanded: " + expandedState
     
      // update the output div  
      dash_clientside.set_props(id, {children})
}

When developing the js function, you can see the data that’s available in the event listener by
starting with `console.log(params). Then open the browser console and you can see how to extract the data you would like:

2 Likes

Exactly what I was looking for! Thank you so much :slightly_smiling_face:

2 Likes