You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material 6.0.1 Tree默认展开及批量展开/折叠功能问询

Angular Material Tree: Default Expand & Bulk Expand/Collapse

Hey there! Great questions about Angular Material Tree—let's walk through how to handle both scenarios you're asking about.

1. Set Tree to Be Expanded by Default

Absolutely! You can make the tree expand all nodes on initial load. The approach is straightforward regardless of whether you're using a FlatTreeControl or NestedTreeControl—you just need to trigger the expansion once the component and tree are fully initialized.

Example with FlatTreeControl

In your component class, use the ngAfterViewInit lifecycle hook to call the tree control's expandAll() method once the view is ready:

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { FlatTreeControl } from '@angular/cdk/tree';
import { MatTreeFlatDataSource, MatTreeFlattener } from '@angular/material/tree';

// Define your flat node interface
interface FlatTreeNode {
  name: string;
  level: number;
  expandable: boolean;
}

@Component({
  selector: 'app-flat-tree',
  templateUrl: './flat-tree.component.html',
  styleUrls: ['./flat-tree.component.css']
})
export class FlatTreeComponent implements OnInit, AfterViewInit {
  private transformer = (node: any, level: number) => {
    return {
      name: node.name,
      level: level,
      expandable: !!node.children && node.children.length > 0
    };
  };

  treeControl = new FlatTreeControl<FlatTreeNode>(
    node => node.level,
    node => node.expandable
  );

  treeFlattener = new MatTreeFlattener(
    this.transformer,
    node => node.level,
    node => node.expandable,
    node => node.children
  );

  dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);

  ngOnInit(): void {
    // Load your tree data here
    this.dataSource.data = [
      {
        name: 'Parent 1',
        children: [{ name: 'Child 1.1' }, { name: 'Child 1.2' }]
      },
      { name: 'Parent 2' }
    ];
  }

  ngAfterViewInit(): void {
    // Expand all nodes once the view is initialized
    this.treeControl.expandAll();
  }

  hasChild = (_: number, node: FlatTreeNode) => node.expandable;
}

Example with NestedTreeControl

The process is nearly identical—call expandAll() on the nested tree control after initialization:

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { NestedTreeControl } from '@angular/cdk/tree';
import { MatTreeNestedDataSource } from '@angular/material/tree';

// Define your nested node interface
interface NestedTreeNode {
  name: string;
  children?: NestedTreeNode[];
}

@Component({
  selector: 'app-nested-tree',
  templateUrl: './nested-tree.component.html',
  styleUrls: ['./nested-tree.component.css']
})
export class NestedTreeComponent implements OnInit, AfterViewInit {
  treeControl = new NestedTreeControl<NestedTreeNode>(node => node.children);
  dataSource = new MatTreeNestedDataSource<NestedTreeNode>();

  ngOnInit(): void {
    this.dataSource.data = [
      {
        name: 'Parent 1',
        children: [{ name: 'Child 1.1' }, { name: 'Child 1.2' }]
      },
      { name: 'Parent 2' }
    ];
  }

  ngAfterViewInit(): void {
    this.treeControl.expandAll();
  }

  hasChild = (_: number, node: NestedTreeNode) => !!node.children && node.children.length > 0;
}

2. Bulk Expand/Collapse All Nodes via Button

You can add buttons to trigger full expansion or collapse by binding their click events to the tree control's built-in methods.

Template Example

Add these control buttons above your tree in your component's template:

<div class="tree-action-buttons">
  <button mat-raised-button color="primary" (click)="expandAllNodes()">Expand All</button>
  <button mat-raised-button color="accent" (click)="collapseAllNodes()">Collapse All</button>
</div>

<!-- Your Angular Material Tree -->
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <!-- Flat tree node template example -->
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
    <li class="mat-tree-node">
      <button mat-icon-button disabled></button>
      {{node.name}}
    </li>
  </mat-tree-node>

  <mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">
    <li>
      <div class="mat-tree-node">
        <button mat-icon-button matTreeNodeToggle>
          <mat-icon class="mat-icon-rtl-mirror">
            {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </button>
        {{node.name}}
      </div>
      <ul [class.mat-tree-invisible]="!treeControl.isExpanded(node)">
        <ng-container matTreeNodeOutlet></ng-container>
      </ul>
    </li>
  </mat-nested-tree-node>
</mat-tree>

Component Methods

Add these simple methods to your component class to handle the button clicks:

expandAllNodes(): void {
  this.treeControl.expandAll();
}

collapseAllNodes(): void {
  this.treeControl.collapseAll();
}

Both FlatTreeControl and NestedTreeControl come with these expandAll() and collapseAll() methods out of the box, so this works seamlessly for either tree type.

内容的提问来源于stack exchange,提问作者saibot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:11:49