getBookOutlineBar
方法将获取节点列表以及打开大纲侧边栏时需要选择的选定节点。如果打开“标题”页面并单击大纲侧边栏,则应展开所有父节点并选择标题。
我在 Angular 8 中使用了 mat 树的嵌套树控制:参见 Stackblitz 示例
getBookOutlineBar() {
let customURL = '';
this.bookService.GetBookOutlineBar(this.bookId, location.hash).subscribe(data => {
this.dataSource.data = data.list;
if (data.selectedNode != null) {
this.selectedNode = data.selectedNode;
this.treeControl.collapseAll();
this.expand(this.dataSource.data, this.selectedNode.UniqueId);
}
})
}
expand(data: BookOutlineBar[], uniqueId: string): any {
data.forEach(node => {
if (node.Children && node.Children.find(c => c.UniqueId === uniqueId)) {
this.treeControl.expand(node);
this.expand(this.treeControl.dataNodes, node.UniqueId);
}
else if (node.Children && node.Children.find(c => c.Children)) {
this.expand(node.Children, uniqueId);
}
});
}
我想展开所选节点的所有父节点,如下图所示:
您的代码
if (node.Children && node.Children.find(c => c.UniqueId === uniqueId)) {
this.treeControl.expand(node);
this.expand(this.treeControl.dataNodes, node.UniqueId);
}
替换为
if (node.Children && node.Children.find(c => c.UniqueId === uniqueId)) {
this.treeControl.expand(node);
this.expand(this.dataSource.data, node.UniqueId);
}
-- 使用数据源数据初始化treeControl
private setDatasource() {
this.treeControl.dataNodes = this.dataSource.data;
}
-- 扩展到选定节点的算法(例如在此代码中:'this.selectedFleet')
// Starting from a list of node
private expandTreeToSelectedNode() {
for (const dataNode of this.treeControl.dataNodes) {
this.expandTreeToSelectedNodeRec(dataNode);
}
}
// Starting from one node
private expandTreeToSelectedNodeRec(current: Node): boolean {
if (current.items.length === 0 && current.id === this.selectedFleet.id) {
this.treeControl.expand(current);
return true;
}
for (const child of current.items) {
if (this.expandTreeToSelectedNodeRec(child)) {
this.treeControl.expand(current);
return true;
}
}
}