如何使用 Angular 8 中 mat 树的嵌套树控件来展开特定子节点的所有父节点?

问题描述 投票:0回答:2

getBookOutlineBar
方法将获取节点列表以及打开大纲侧边栏时需要选择的选定节点。
我已经实现了 Expand 方法来展开所有父节点,但它只是展开一个特定节点,而不是所有父节点。

如果打开“标题”页面并单击大纲侧边栏,则应展开所有父节点并选择标题。
我在 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);
    }
  });
}

我想展开所选节点的所有父节点,如下图所示:

angular tree treeview material-ui mat
2个回答
2
投票

您的代码

 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);
          }

0
投票

-- 使用数据源数据初始化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;
      }
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.