Search code examples
angulartreetreeviewmaterial-uimat

How to expand all parent node of particular child node using nested tree control of mat tree in angular 8?


getBookOutlineBar method will take a list of nodes and the selected node which needs to be selected when sidebar of outline opens.
I have implemented expand method to expand all parent node but it is only expanding one particular node, not all parent nodes.

If page "Heading" is opened and I click on outline sidebar than all parent nodes should be expanded and heading should be selected.
I have used nested tree control of mat tree in angular 8: see Stackblitz example

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

I want to expand all parent nodes of selected node like in this image:

Desired state


Solution

  • Your code

     if (node.Children && node.Children.find(c => c.UniqueId === uniqueId)) {
                this.treeControl.expand(node);
                this.expand(this.treeControl.dataNodes, node.UniqueId);
              }
    

    Replace with

     if (node.Children && node.Children.find(c => c.UniqueId === uniqueId)) {
                this.treeControl.expand(node);
                this.expand(this.dataSource.data, node.UniqueId);
              }