我正在实现角度/材质树组件,并且遇到一些问题。保存对树的更改后,我正在重置支持树的数据(有效),但是应用程序变得异常缓慢,扩展节点可能需要8秒钟。
让这更奇怪的是,实际上操纵数据源的代码在其他地方运行,例如向树中添加新的子级-我们希望更新UI,这不会造成问题。只有在保存时,应用程序才会变慢。
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);
}
编辑:
更改刷新树以创建全新的数据源可解决缓慢的问题(内存泄漏?),但不会在UI中添加未显示的子对象。尽管孩子在展平的树上,但是应该显示。
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);
}
编辑:这是支持它的html。很标准。
<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>
答案 0 :(得分:4)
尽管公认的答案似乎可以提高速度,但最终为我做到的解决方案(在Angular 8中)是:
https://stackoverflow.com/a/59655114/134120
从官方示例中更改该行:
<ul [class.example-tree-invisible]="!treeControl.isExpanded(node)">
对此:
<ul *ngIf="treeControl.isExpanded(node)">
以使折叠的子树根本不会加载到DOM中。
答案 1 :(得分:3)
我花了几个小时才开始工作,但这是我所做的更改:
// 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;
我在这里发现的展示儿童的问题:https://github.com/angular/material2/issues/11381