How to implement Virtual scroll on material tree grand child level
Asked Answered
M

1

1

I have an angular mat-tree with parent, child and grand child level. On clicking of child I am adding grandchild in it. But grandchild having huge data upto 4k records. Which is making tree extremely slow. My code as below

<div *ngIf="isGrandChildLoaded"><mat-spinner></mat-spinner></div>
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <!-- This is the tree node template for leaf nodes -->
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>
    <!-- use a disabled button to provide padding for tree leaf -->
    <button mat-icon-button disabled></button>
    {{node.name}}
  </mat-tree-node>
  <!-- This is the tree node template for expandable nodes -->
  <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding>
    <button mat-icon-button matTreeNodeToggle
            [attr.aria-label]="'toggle ' + node.name">
      <mat-icon class="mat-icon-rtl-mirror" (click)="clickTreeNode(node)">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.name}}
  </mat-tree-node>
</mat-tree>

Please note what I have tried in stackblitz: My code

I have noted virtual scroll will be the best solution in this case. And I have saw an example: Refernce

But in example it is having virtual-scroll in whole tree level with full dataSource.

How Can add Virtual scroll in grandchild level with 10 elements at a time. So it wont freeze DOM and Tree. Please guide me...

Micropaleontology answered 9/5, 2019 at 16:57 Comment(0)
C
1

To virtualize a tree, map the hierarchical data to a flat list such that each item includes original data plus hierarchy info.

This data, for example,

    [{ 
        name: 'item 1', 
        children: [{ 
            name: 'sub item 1', 
            children: [{ 
                name: 'grandchild 1', 
                children: [] 
            }]
        }]
    }]

Would become

    [
        { name: 'item 1', depth: 0, parent: null },
        { name: 'sub item 1', depth: 1, parent: /*ref to 'item 1'*/ },
        { name: 'grandchild 1', depth: 2, parent: /*ref to 'sub item 1'*/ }
    ]

With the data flattened, it is can be virtualized the same as any flat list. Use the depth to indent elements, and use the parent to toggle child item inclusion in the list based on parent expand state.

Also, here's an angular based implementation that I just published. https://github.com/gjcampbell/ooffice/tree/master/projects/of-tree

Closestool answered 4/1, 2020 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.