I am implementing the angular/material tree component and having some problems. After saving changes to the tree I am resetting the data backing the tree (which works) however the app then becomes incredibly slow, expanding nodes can take about 8 seconds.
What makes this even weirder is that the code that actually manipulates the data source is run in other places, such as adding a new child to the tree - we want the UI to update, and this does not cause a problem. It is only when saving that the app becomes slow.
save(): void {
const trees = this.flattenedTree.filter(node => this.isRootNode(node));
this.serviceThatHasNoSideEffects.save(trees)
.then(result => {
this.tree = result;
this.flattenedTree = this.getFlattenedTree();
this.refreshTree();
});
}
private refreshTree() {
const data: any[] = this.flattenedTree
.filter(x => this.isRootNode(x))
.filter(x => x.children.length > 0 || x.id === this.focusId);
this.nestedDataSource.data = null;
this.nestedDataSource.data = data;
const focusNode = this.getNode(this.focusId);
this.nestedTreeControl.expand(focusNode);
}
private addChild(parentNode: any, childNode: any) {
if (!this.getNode(parentNode)) {
this.flattenedTree.push(parentNode);
}
if (!this.getNode(childNode)) {
this.flattenedTree.push(childNode);
}
parentNode.children.push(childNode);
this.refreshTree();
this.nestedTreeControl.expand(parentNode);
}
EDIT:
changing refresh tree to create a completely new data source solves the slow issue (memory leak?) but not adding a child isnt displaying in the UI. Although the child is there on the flattened tree so should be displayed.
private refreshTree() {
const data: any[] = this.flattenedTree
.filter(x => this.isRootNode(x))
.filter(x => x.children.length > 0 || x.id === this.focusId);
this.nestedDataSource = new MatTreeNestedDataSource<theTreeType>();
this.nestedDataSource.data = data;
const focusNode = this.getNode(this.focusId);
this.nestedTreeControl.expand(focusNode);
}
EDIT: here is the html backing it. pretty standard.
<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
<li class="mat-tree-node">
<button mat-icon-button disabled></button>
{{node.uniqueName}}
</li>
</mat-tree-node>
<!--when has nested child-->
<mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">
<li>
<div class="mat-tree-node">
<button mat-icon-button matTreeNodeToggle>
<mat-icon>
{{nestedTreeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.uniqueName}}
</div>
<ul [class.invisible]="!nestedTreeControl.isExpanded(node)">
<ng-container matTreeNodeOutlet></ng-container>
</ul>
</li>
</mat-nested-tree-node>
</mat-tree>
it took me a few hours to get it working but here is the change I made:
The displaying children issue I found here: https://github.com/angular/material2/issues/11381