我正在实现角度/材料树组件并遇到一些问题。保存对树的更改后,我正在重置支持树的数据(有效),但是应用程序变得非常慢,扩展节点可能需要大约 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);
}
EDIT:
更改刷新树以创建全新的数据源解决了缓慢的问题(内存泄漏?),但不添加子项不会在 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>
尽管接受的答案似乎提供了一些速度改进,但最终为我完成的解决方案(在 Angular 8 中)是这样的:
https://stackoverflow.com/a/59655114/134120 https://stackoverflow.com/a/59655114/134120
更改官方示例中的行:
<ul [class.example-tree-invisible]="!treeControl.isExpanded(node)">
to this:
<ul *ngIf="treeControl.isExpanded(node)">
这样折叠的子树根本不会加载到 DOM 中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)