Why is my angular app becoming very slow after changing the data backing a mat-tree?

it took me a few hours to get it working but here is the change I made:

// cdk tree that mat tree is based on has a bug causing children to not be rendered in the UI without first setting the data to null
this.nestedDataSource.data = null;
// mat-tree has some sort of memory leak issue when not instantiating a new MatTreeNestedDataSource which causes the app to become very slow
this.nestedDataSource = new MatTreeNestedDataSource<LocationHierarchyNodeDataModel>();
this.nestedDataSource.data = data;

The displaying children issue I found here: https://github.com/angular/material2/issues/11381


Although the accepted answer seems to offer some speed improvement, the solution that finally did it for me (in Angular 8) is this:

https://stackoverflow.com/a/59655114/134120

Change the line from the official examples:

<ul [class.example-tree-invisible]="!treeControl.isExpanded(node)">

to this:

<ul *ngIf="treeControl.isExpanded(node)">

so that collapsed subtrees are not loaded in the DOM at all.