# Managing the tree expand/collapse state

> Learn how to control which tree nodes are expanded or collapsed

Canonical page: https://infinite-table.com/angular/docs/learn/tree-grid/tree-expand-and-collapse-state

By default, the tree will be rendered with all nodes expanded. This is fine for basic use cases, but as soon as you go into more complex scenarios, you will want to control which nodes are expanded or collapsed.

This is easy to achieve via the [`defaultTreeExpandState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultTreeExpandState) prop. This is an uncontrolled prop and allows you to initially specify the expand/collapse state of the tree - all subsequent user updates will result in the tree state being updated to match the UI actions.

**Example: Specifying an initial tree expand state**

```ts
import { Component } from '@angular/core';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  DataSourceApi,
  InfiniteTableColumn,
  TreeExpandStateValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const defaultTreeExpandState: TreeExpandStateValue = {
  defaultExpanded: true,
  collapsedPaths: [
    ['1', '10'],
    ['3', '31'],
  ],
  expandedPaths: [['3']],
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '30',
          name: 'Music - empty',
          sizeInKB: 0,
          type: 'folder',
          children: [],
        },
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <infinite-tree-data-source
      (ready)="dataSourceApi = $event"
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [defaultTreeExpandState]="defaultTreeExpandState"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button (click)="dataSourceApi!.treeApi.expandAll()">Expand all</button>
        <button (click)="dataSourceApi!.treeApi.collapseAll()">
          Collapse all
        </button>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly defaultTreeExpandState = defaultTreeExpandState;

  protected dataSourceApi: DataSourceApi<FileSystemNode> | null = null;
}
```

## Understanding the tree expand state

You can specify the expand/collapse state of the tree in two ways:

1. With node paths (recommended)

When using node paths, the object should have the following properties:

- `defaultExpanded`: `boolean` - whether the tree nodes are expanded by default or not.
- `collapsedPaths`: `string[]` - when `defaultExpanded` is `true`, this is a mandatory prop.
- `expandedPaths`: `string[]` - when `defaultExpanded` is `false`, this is a mandatory prop.

```tsx
const treeExpandState = {
  defaultExpanded: true,
  collapsedPaths: [
    ['1', '10'],
    ['2', '20'],
    ['5']
  ],
  expandedPaths: [
    ['1', '4'],
    ['5','nested node in 5'],
  ],
};
```

2. With node ids

When using node ids, the object should have the following properties:

- `defaultExpanded`: `boolean` - whether the tree nodes are expanded by default or not.
- `collapsedIds`: `string[]` - when `defaultExpanded` is `true`, this is a mandatory prop.
- `expandedIds`: `string[]` - when `defaultExpanded` is `false`, this is a mandatory prop.

```tsx
const treeExpandState = {
  defaultExpanded: true,
  collapsedIds: ['1', '2', '5'],
  expandedIds: ['10', '20', 'nested node in 5'],
};
```

## Reacting to user actions

You can listen to the user interactions with the tree by using the [`(treeExpandStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onTreeExpandStateChange) output. It emits the new tree state whenever the user expands or collapses a node.

In addition to this output, you can also use the following:

 - [`(nodeExpand)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeExpand) - emits the path of the expanded node
 - [`(nodeCollapse)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeCollapse) - emits the path of the collapsed node

When you also need the second argument of these callbacks (`{dataSourceApi, nodePath, nodeState}` and `{dataSourceApi}`), bind a function to the input of the same name instead: `[onTreeExpandStateChange]="onTreeExpandStateChange"`, `[onNodeExpand]`, `[onNodeCollapse]`.

The [`(nodeExpand)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeExpand) and [`(nodeCollapse)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeCollapse) callbacks are called when a node is expanded or collapsed, respectively - either via user interaction or by an API call. However, they will not be called when the [`expandAll`](https://infinite-table.com/docs/reference/tree-api/index.md#expandAll) or [`collapseAll`](https://infinite-table.com/docs/reference/tree-api/index.md#collapseAll) methods are called.

## Using controlled expand/collapse state

If you want maximum control over the collapse/expand state, you should use the controlled [`[(treeExpandState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeExpandState) prop.

This will allow you to own the collapse/expand state entirely. [`[(treeExpandState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeExpandState) is a model: bind it two-way to a signal, and the grid writes the new state back to it after user actions or API calls. To react to the change, use the [`(treeExpandStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onTreeExpandStateChange) output.

**Example: Using controlled expand/collapse state**

```ts
import { Component, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  TreeExpandStateValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '30',
          name: 'Music',
          sizeInKB: 0,
          type: 'folder',
          children: [],
        },
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid, JsonPipe],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [(treeExpandState)]="treeExpandState"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button
          (click)="
            treeExpandState.set({ defaultExpanded: true, collapsedPaths: [] })
          "
        >
          Expand all
        </button>
        <button
          (click)="
            treeExpandState.set({
              defaultExpanded: false,
              expandedPaths: [],
            })
          "
        >
          Collapse all
        </button>
        <div>
          Current tree expand state:
          <pre>{{ treeExpandState() | json }}</pre>
        </div>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly treeExpandState = signal<TreeExpandStateValue>({
    defaultExpanded: true,
    collapsedPaths: [['1', '10'], ['3']],
  });
}
```

When using controlled [`[(treeExpandState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeExpandState), you no longer need to use API calls.

When you need to expand all nodes, simply set the [`[(treeExpandState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeExpandState) to `{defaultExpanded: true, collapsedPaths: []}`.

When you need to collapse all nodes, simply set the [`[(treeExpandState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeExpandState) to `{defaultExpanded: false, expandedPaths: []}`.
