且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular Material 6.0.1默认打开树并展开/折叠全部

更新时间:2023-12-02 18:24:16

MatTree的treeControl提供了expandAll方法,可用于扩展所有树节点,而collapseAll方法可用于关闭所有树节点./p>

您可以通过ViewChild实例化MatTree,并在ngAfterViewInit生命周期钩子中调用expandAll以使其默认展开.

@ViewChild('tree') tree;

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

从模板调用的源示例:

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

请参见 示例 .

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

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.