Angular material CDK tree component with virtual scroll

angularangular-cdkangular-material2angular6

Angular Material CDK tree component documentation says:

"Flat trees are generally easier to style and inspect. They are also more friendly to scrolling variations, such as infinite or virtual scrolling"

Any ideas how to apply virtual scrolling to CDK flat tree?

I have a massive tree to render and right now it is so slow and when I open all nodes recursively it will crash

I tried < cdk-virtual-scroll-viewport > @angular/cdk-experimental but did not figure it out how to integrate it with tree component

Best Answer

I know this is old, but I came across this thread while trying to figure out the same exact thing, and after much experimentation, I've figured out a basic working example of a virtually scrolling flat tree that requires VERY LITTLE MODIFICATION if you already have a working cdk-tree

The key to my solution was to abandon the cdk-tree directives and use my MatTreeFlatDataSource and FlatTreeControl directly with *cdkVirtualFor. You probably already have these objects set up to pass as inputs into cdk-tree. cdk-tree is actually just a very light wrapper around these two objects that are doing all of the heavy lifting.

Here's a stackblitz, for a more concrete example: https://stackblitz.com/edit/angular-b5nkkd?file=src/app/app.component.html

Here's what it contains:

  • Two scrolling flat trees that draw from the same underlying data source and are controlled by the same underlying tree control (i.e, they hold the same data and whatever you do to one tree will be reflected in the other tree as well)

  • The first tree uses cdk-tree directives, but I couldn't figure out how to get it to work with CDK virtual scroll so it renders all the nodes

  • The second tree does NOT use cdk-tree, but I was able to get virtual scrolling to work cleanly with very little changes. As a result, you have to do styling and some basic logic yourself, but if you look at the difference in template code in the stackblitz, you'll see that it's not so bad.

  • I'm displaying the number of nodes each scroll container is rendering to demonstrate that virtual scrolling is working in one and not the other