2

I have a Angular Material Nested tree. I'm trying to create a button to expand/collapse, but I'm getting the following error:
ERROR TypeError: Cannot read property 'reduce' of undefined

I have tried it using HTML:

<button (click)="ahtree.treeControl.collapseAll()">collapseAll</button>

<button (click)="treeControl.expandAll()">expandAll</button>


<mat-tree #ahtree [dataSource]="AccountRelTypeTreeDataSource" [treeControl]="treeControl" class="example-tree">
  <!-- This is the tree node template for leaf nodes -->
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
    <li class="mat-tree-node">
      <!-- use a disabled button to provide padding for tree leaf -->
      <button mat-icon-button disabled></button>
      <p">{{node.displayName}}</p>
    </li>
  </mat-tree-node>
  // The rest...
  ...

Or with typescript:

  // Trees:
  @ViewChild('ahtree') ahtree;
  selectedTab = 0;

  // Datasource
  treeControl = new NestedTreeControl<TreeNode>(node => node.children);
  DataSource = new MatTreeNestedDataSource<TreeNode>();

  ...

   ngAfterViewInit() {
    this.ahtree.treeControl.expandAll();
   }

I read https://material.angular.io/components/tree/overview#treecontrol, but I still don't seem to get it to work.

Does anyone know how to do this with a Nested Tree?

1 Answer 1

5

You didn't show the full stack trace, but I suppose the error is the same one as described in this Github ticket. The solution given by user devversion worked for me. See this anchor in the same ticket.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this Answer referencing GitHub issue #12469. In August 2022 GuillaumeChata added a very similar approach to that (still Open) Issue, setting both objects to TREE_DATA in the constructor: constructor() { this.dataSource.data = TREE_DATA; /* work-around to avoid an undefined dataNodes even after ViewInit*/ this.treeControl.dataNodes = TREE_DATA; } That was all I needed. He included ChangeDetectorRef in the constructor in his example but that doesn't appear to be necessary to the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.