# Using tree selection

> Learn how to leverage the tree and specify the tree selection state

Canonical page: https://infinite-table.com/angular/docs/learn/tree-grid/tree-selection

When using a tree grid, a common use-case is to allow users to select nodes, both parent and child nodes.

The `<TreeDataSource>` component allows you to specify an initial tree selection, via the `defaultTreeSelection` prop.

When using [`defaultTreeSelection`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultTreeSelection) or its controlled counterpart [`[(treeSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelection), if no [`selectionMode`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#selectionMode) is specified, the selection mode will default to `"multi-row"`.

If you enable selection, don't forget to specify which column should render a selection checkbox, by using [renderSelectionCheckBox=true](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.renderSelectionCheckBox).

```ts
import type { TreeSelectionValue } from '@infinite-table/infinite-angular';

// Default selection is false, with some selected node paths: ['1'] and ['2', '20']
// however, node ['1', '10'] is deselected
const treeSelectioDefaultDeselected: TreeSelectionValue = {
  defaultSelection: false,
  selectedPaths: [['1'], ['2', '20']],
  deselectedPaths: [['1', '10']],
};
```

```tsx
// Default selection is true, with some deselected node paths: ['2'] and ['3']
// however, inside ['3'], we have a selected node ['3','30','301']
const treeSelectionDefaultSelected: TreeSelectionValue = {
  defaultSelection: true,
  deselectedPaths: [['2'], ['3']],
  selectedPaths: [['3','30','301']],
};
```

**Example: Using default tree selection**

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

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  DataSourceApi,
  InfiniteTableColumn,
  TreeSelectionValue,
} 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,
    renderSelectionCheckBox: 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 defaultTreeSelection: TreeSelectionValue = {
  defaultSelection: true,
  deselectedPaths: [
    ['1', '10'],
    ['3', '31'],
  ],
  selectedPaths: [['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: '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"
      [defaultTreeSelection]="defaultTreeSelection"
    >
      <div
        style="color: var(--infinite-cell-color); padding: 10px; display: flex; gap: 10px"
      >
        <button (click)="dataSourceApi!.treeApi.selectAll()">Select all</button>
        <button (click)="dataSourceApi!.treeApi.deselectAll()">
          Deselect 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 defaultTreeSelection = defaultTreeSelection;

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

When using [uncontrolled tree selection](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultTreeSelection), the `<TreeDataSource />` will manage the selection state internally, and will update it as a result of user actions. If you want to change the selection, you can use [the Tree API](https://infinite-table.com/docs/reference/tree-api/index.md) to do so: [`selectNode`](https://infinite-table.com/docs/reference/tree-api/index.md#selectNode), [`deselectNode`](https://infinite-table.com/docs/reference/tree-api/index.md#deselectNode), [`selectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#selectAll), [`deselectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#deselectAll), etc.

## Selecting nodes with the mouse and keyboard

Users select nodes just like rows in a grouped table - see [using your mouse and keyboard to select rows](https://infinite-table.com/angular/docs/learn/selection/row-selection.md#using-your-mouse-and-keyboard-to-select-rows). Parent nodes work like group rows:

- clicking a node selects it, and only it - clicking a parent node selects all its nodes;
- `cmd`/`ctrl` + click toggles a node, keeping the rest of the selection;
- `shift` + click selects the range of nodes displayed from the last clicked node to the clicked one. A collapsed parent node in the range is selected with all its nodes, while an expanded one follows its children - only its nodes inside the range are selected. The starting node keeps what its own click selected, so a parent node stays selected with all its nodes;
- the spacebar works like a click on the active row, and `shift` + spacebar selects a range.

The [`multiRowSelectionWith`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#multiRowSelectionWith) prop decides whether clicks select nodes while a visible column shows a selection checkbox. With `'checkbox'` (the default), users select nodes with the checkboxes (`shift` + a checkbox selects a range) and the spacebar toggles the active node. With `'click'`, clicks select nodes as well.

Clicking the expand/collapse icon of a parent node doesn't change the selection, and nodes that can't be selected - like read-only parent nodes (see [`isNodeReadOnly`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#isNodeReadOnly)) - are skipped.

With single-row selection, clicking a node - a parent node too - selects it, while `cmd`/`ctrl` + click and the spacebar toggle it.

Click `Report.docx`, then `shift` + click `unknown.txt` - the collapsed `Private` folder is selected with all its files. Use the buttons to show the selection checkboxes and to choose how users select nodes.

**Example: Selecting nodes with the mouse and keyboard**

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

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

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

const defaultTreeSelection: TreeSelectionValue = {
  defaultSelection: false,
  selectedPaths: [],
};

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

const nodes: FileSystemNode[] = [
  {
    id: '1',
    name: 'Documents',
    sizeInKB: 1200,
    type: 'folder',
    children: [
      { id: '11', name: 'Report.docx', sizeInKB: 210, type: 'file' },
      {
        id: '10',
        name: 'Private',
        sizeInKB: 100,
        type: 'folder',
        children: [
          { id: '100', name: 'Vacation.docx', sizeInKB: 120, type: 'file' },
          { id: '101', name: 'CV.pdf', sizeInKB: 108, type: 'file' },
        ],
      },
    ],
  },
  {
    id: '2',
    name: 'Desktop',
    sizeInKB: 1000,
    type: 'folder',
    children: [
      { id: '20', name: 'unknown.txt', sizeInKB: 100, type: 'file' },
      { id: '21', name: 'notes.txt', sizeInKB: 20, type: 'file' },
    ],
  },
  {
    id: '3',
    name: 'Media',
    sizeInKB: 1000,
    type: 'folder',
    children: [
      {
        id: '31',
        name: 'Videos',
        sizeInKB: 5400,
        type: 'folder',
        children: [
          { id: '310', name: 'Vacation.mp4', sizeInKB: 108, type: 'file' },
        ],
      },
    ],
  },
];

const names: Record<string, string> = {};
const collectNames = (list: FileSystemNode[]) =>
  list.forEach((node) => {
    names[node.id] = node.name;
    if (node.children) {
      collectNames(node.children);
    }
  });
collectNames(nodes);

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <div
      style="color: var(--infinite-cell-color); padding: 10px; display: flex; flex-wrap: wrap; gap: 10px"
    >
      <button (click)="checkbox.set(!checkbox())">
        {{ checkbox() ? 'Hide' : 'Show' }} selection checkboxes
      </button>
      <button
        (click)="selectWith.set(selectWith() === 'click' ? 'checkbox' : 'click')"
      >
        multiRowSelectionWith: {{ selectWith() }}
      </button>
    </div>
    <div style="color: var(--infinite-cell-color); padding: 10px">
      Selected files: {{ selectedFiles().join(', ') || 'none' }}
    </div>
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="nodes"
      selectionMode="multi-row"
      [defaultTreeExpandState]="defaultTreeExpandState"
      [defaultTreeSelection]="defaultTreeSelection"
      [onTreeSelectionChange]="onTreeSelectionChange"
    >
      <infinite-tree-grid
        [columns]="columns()"
        [multiRowSelectionWith]="selectWith()"
      />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly nodes = nodes;
  protected readonly defaultTreeExpandState = defaultTreeExpandState;
  protected readonly defaultTreeSelection = defaultTreeSelection;

  protected readonly checkbox = signal(false);
  protected readonly selectWith =
    signal<InfiniteTablePropMultiRowSelectionWith>('checkbox');
  protected readonly selectedFiles = signal<string[]>([]);

  protected readonly columns = computed<
    Record<string, InfiniteTableColumn<FileSystemNode>>
  >(() => ({
    name: {
      field: 'name',
      header: 'Name',
      renderTreeIcon: true,
      renderSelectionCheckBox: this.checkbox(),
    },
    type: { field: 'type', header: 'Type' },
    size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
  }));

  // a function input: it also gets the selection state, as the second argument
  protected readonly onTreeSelectionChange: DataSourcePropOnTreeSelectionChange_MultiNode<FileSystemNode> =
    (_selection, { treeSelectionState }) => {
      this.selectedFiles.set(
        treeSelectionState
          .getSelectedLeafNodePaths()
          .map((path) => names[path[path.length - 1]]),
      );
    };
}
```

## Selecting nodes when the tree is filtered

When some nodes are filtered out (see [`treeFilterFunction`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeFilterFunction)), use the [`multiRowSelectionTarget`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#multiRowSelectionTarget) prop to decide which nodes the header checkbox, the parent node checkboxes and [`selectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#selectAll)/[`deselectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#deselectAll) act on:

- `'all'` (the default) - they act on all the leaf nodes, including the ones that are filtered out. A parent node checkbox is only checked when all its leaf nodes are selected.
- `'visible'` - they act only on the leaf nodes that pass the filter. Filtered out nodes keep their current selection. A parent node checkbox is checked when all its visible leaf nodes are selected.

When no nodes are filtered out, both values behave the same.

The tree is filtered to only show `.docx` files. Select a folder or click "Select all", then clear the filter to see which files were selected with each [`multiRowSelectionTarget`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#multiRowSelectionTarget) value.

**Example: Choosing which nodes the selection acts on when the tree is filtered**

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

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

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

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: {
    field: 'name',
    header: 'Name',
    renderTreeIcon: true,
    renderSelectionCheckBox: true,
  },
  type: { field: 'type', header: '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' },
            { id: '101', name: 'Vacation.docx', sizeInKB: 120, type: 'file' },
            { id: '102', name: 'CV.pdf', sizeInKB: 108, type: 'file' },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        { id: '20', name: 'unknown.txt', sizeInKB: 100, type: 'file' },
        { id: '21', name: 'Notes.docx', sizeInKB: 50, type: 'file' },
      ],
    },
  ];
  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"
      selectionMode="multi-row"
      [multiRowSelectionTarget]="target()"
      [treeFilterFunction]="filter() ? treeFilterFunction() : undefined"
    >
      <div
        style="color: var(--infinite-cell-color); padding: 10px; display: flex; gap: 10px; align-items: center"
      >
        <label>
          multiRowSelectionTarget:
          <select (change)="onTargetChange($event)">
            <option value="all" [selected]="target() === 'all'">all</option>
            <option value="visible" [selected]="target() === 'visible'">
              visible
            </option>
          </select>
        </label>
        <input
          placeholder="Filter files by name"
          [value]="filter()"
          (input)="onFilterInput($event)"
        />
        <button (click)="dataSourceApi!.treeApi.selectAll()">Select all</button>
        <button (click)="dataSourceApi!.treeApi.deselectAll()">
          Deselect all
        </button>
      </div>

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

  protected dataSourceApi: DataSourceApi<FileSystemNode> | null = null;
  protected readonly target =
    signal<DataSourcePropMultiRowSelectionTarget>('visible');
  protected readonly filter = signal('.docx');

  // a new function whenever the filter text changes, so the tree is filtered again
  protected readonly treeFilterFunction = computed(() => {
    const currentFilter = this.filter();

    return ({
      data,
      filterTreeNode,
    }: {
      data: FileSystemNode;
      filterTreeNode: (data: FileSystemNode) => FileSystemNode | boolean;
    }) => {
      if (!Array.isArray(data.children)) {
        return data.name.toLowerCase().includes(currentFilter.toLowerCase());
      }
      return filterTreeNode(data);
    };
  });

  protected onTargetChange(event: Event) {
    this.target.set(
      (event.target as HTMLSelectElement)
        .value as DataSourcePropMultiRowSelectionTarget,
    );
  }

  protected onFilterInput(event: Event) {
    this.filter.set((event.target as HTMLInputElement).value);
  }
}
```

## Reacting to user actions

To listen to selection changes, you can use the [`(treeSelectionChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onTreeSelectionChange) output - it emits the new tree selection. To also get the second argument of the callback (with the `treeSelectionState` - the mouse and keyboard example above uses it to show the selected files), bind a function to the `[onTreeSelectionChange]` input instead.

This callback is called both when the user interacts with the grid, and when you use the [Tree API](https://infinite-table.com/docs/reference/tree-api/index.md) to change the selection.

## Using controlled tree selection

[`[(treeSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelection) is a model: bind it two-way to a signal, and the grid writes the user's selection back to it. To react to the change, use the [`(treeSelectionChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onTreeSelectionChange) output.

Controlled tree selection also gives you a more declarative way to manage the selection state.
You no longer have to call [Tree API](https://infinite-table.com/docs/reference/tree-api/index.md) methods to change the selection. Simply pass a new tree selection state object to the [`[(treeSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelection) prop and the tree grid will be updated accordingly.

For example, if you want to select all nodes, set the [`[(treeSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelection) prop to:

```tsx
{
  defaultSelection: true,
  deselectedPaths: [],
}
```

For deselecting all nodes, the value should be:

```tsx
{
  defaultSelection: false,
  selectedPaths: [],
}
```

Using controlled tree selection also gives you an easy way to restore a previously saved tree selection at any point in time.

**Example: Using controlled tree selection**

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

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  TreeSelectionValue,
} 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,
    renderSelectionCheckBox: 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: '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"
      [(treeSelection)]="treeSelection"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button
          (click)="
            treeSelection.set({
              defaultSelection: false,
              selectedPaths: [],
            })
          "
        >
          Deselect all
        </button>
        <button
          (click)="
            treeSelection.set({
              defaultSelection: true,
              deselectedPaths: [],
            })
          "
        >
          Select all
        </button>
        <div style="overflow: auto; height: 10vh; min-height: 200px">
          Current tree selection:
          <pre>{{ treeSelection() | 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 treeSelection = signal<TreeSelectionValue>({
    defaultSelection: false,
    selectedPaths: [['1', '10'], ['3']],
  });
}
```
