Tree-data with ag-grid Community

tree-data with ag-grid

demo: https://ag-grid-tree.codeb.online

ag-grid is a feature-rich library and I have used it on many projects. I was working on POC for 1 project and we needed to represent tree data inside the table.

tree-data can be easily achieved using enterprise edition, but since it was just a POC I tried to achieve it using community version with custom code.

Github: https://github.com/riddheshganatra/ag-grid-tree

Let's start with code:

index.html

index.html

We are loading ag-grid community library, font awesome and main js.

main.js

  1. columnDefs

We want to add onclick event of first column and are using cellRenderer property.

2) input data

rowdata is input data to ag-grid. Its recursive data with childrens array.

3) We need to add unique id in every record:

Simple recursive function to add customId key in every record.

4)Grid options

5) MedalCellRenderer

MedalCellRenderer takes care of adding click listener, add left padding depending on level(level will be calculated by our custom function explained below) and displaying a correct icon.

Here we can see we are using 3 custom keys from user data: expanded, level and customId.

When a particular node is clicked, we call updateData function and pass customId of clicked node

6) updateData()

updateData finds data recursively by customId and toggles expanded state of it.

Then we recreate rowDataExpanded using makeDataRecursive function.

7) recursiveFindById and makeDataResurcive

8) final step to setup grid

Wrapping up

Obviously ag-grid enterprise version has lots of complex features and totally worth it, I just wanted to share this alternative for a simple use case.

Software Architect, Full Stack Web developer, MEAN/MERN stack, Microservices, etc