Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 6.0.1 Tree default opened and expand/collapse all

I'm using the Angular Material Tree in my project. Is it possible to have the tree opened by default.

And could there be a way to expand/collapse all the nodes at once (eg. with a button)

https://material.angular.io/components/tree/overview

like image 924
saibot Avatar asked May 11 '18 07:05

saibot


1 Answers

MatTree's treeControl provide a expandAll method which you can use to expand all tree nodes, and collapseAll to close all tree nodes.

You can can instance of MatTree via ViewChild and call expandAll in ngAfterViewInit life hook to make it expand by default.

@ViewChild('tree') tree;

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

Source example for calling from template:

<button (click)="tree.treeControl.collapseAll()">collapseAll</button>
<button (click)="tree.treeControl.expandAll()">expandAll</button>
<mat-tree #tree [dataSource]="dataSource" [treeControl]="treeControl">
  ...
<mat-tree>

see example.

like image 109
Pengyy Avatar answered Oct 13 '22 19:10

Pengyy