gpt4 book ai didi

angular - 树 : How to keep opened states when tree updated

转载 作者:太空狗 更新时间:2023-10-29 18:28:34 24 4
gpt4 key购买 nike

当我将新数据设置为 this.dataSource.data 时,我需要保持树节点打开/关闭状态。新数据与旧数据非常相似 - 它只是添加/删除了一个或几个最低级别的节点。

我的想法是将节点展开记录到ReplaySubject,并重放展开队列。它应该工作,但这是非常丑陋的方式。

我希望这里有更优雅的方法来解决我的问题。

最佳答案

我有一个数据对象的层次结构来显示在 Material 树中。每个数据对象都被转换为包含原始数据对象的 ID 和 ParentID 的 TreeNodeModel。在更新数据源的方法中保存/恢复节点的展开状态:

// Method that updates the data source
public updateDataSource(dataObjects: SomeDataObject) {

// save node's expanded state
const expandedNodesIds: string[] = [];
if (this.treeControl.dataNodes) {
this.treeControl.dataNodes.forEach((node: TreeNodeModel) => {
if (this.treeControl.isExpandable(node) && this.treeControl.isExpanded(node)) {
expandedNodesIds.push(node.id);
}
});
}

// update data source
this.treeDataSource.data = dataObjects;

// restore node's expanded state
this.treeControl.dataNodes
.filter(node => this.isActive(node) || expandedNodesIds.find(id => id === node.id))
.forEach(nodeToExpand => {
this.expandNode(nodeToExpand);
});
}

// Method that expands the node (if not a leave) and its parent nodes (if any) using the TreeControl
private expandNode(treeNode: TreeNodeModel | undefined): void {
if (!treeNode) {
return;
}

if (this.treeControl.isExpandable(treeNode)) {
this.treeControl.expand(treeNode);
}

const parentId = treeNode.parentId ? treeNode.parentId : undefined;
this.expandNode(this.treeControl.dataNodes.find(node => node.id === parentId));
}

interface TreeNodeModel {
expandable: boolean;
level: number;
id: string;
parentId: string;
// most probably some more custom data ;)
}

关于angular - 树 : How to keep opened states when tree updated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53280079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com