Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update my mat-tree without it rerendering?

My mat tree redraws initializes itself on datasource data change using a BehaviorSubject.

I am using an observable that i update form time to time in order to update the tree data generated by a FlatTreeControl.

The code is pretty basic and easy to understand so I don't see the issue.

I tried using a simplified version of the angular flat tree example on stackBlitz: https://stackblitz.com/angular/rlqvokgplrko?file=app%2Ftree-checklist-example.ts

Here is my version: https://stackblitz.com/edit/create-iq2meg

What i expect is that as in the official mat-tree example, the data is updated dynamically WITHOUT having to redraw the entire tree and having it collapse on me each time.

like image 371
lolplayer101 Avatar asked May 09 '19 12:05

lolplayer101


1 Answers

We may use a workaround for this as mentioned in GitHub by @danielkuhlwein

Save expanded nodes to a list before doing any re-rendering:

saveExpandedNodes() {
    this.expandedNodes = new Array<BulletFlatNode>();
    this.treeControl.dataNodes.forEach(node => {
        if (node.expandable && this.treeControl.isExpanded(node)) {
            this.expandedNodes.push(node);
        }
    });
}

And then restore the expanded nodes after doing the re-rendering:

restoreExpandedNodes() {
    this.expandedNodes.forEach(node => {
        this.treeControl.expand(this.treeControl.dataNodes.find(n => n.id === node.id));
    });
}
like image 129
Oleg K Avatar answered Oct 03 '22 22:10

Oleg K