forty-cdk
llms.txt

Primitives

Tree

A nested tree view for hierarchical data: expandable nodes with roving-tabindex navigation, single or multi selection, and typeahead.

forty-cdk/tree WAI-ARIA APG

Walk the tree with the arrow keys: right expands a node and left collapses it. Each node carries data-state, data-selected and data-highlighted.

  • src
    • app
      • app.ts
      • app.html
      • app.css
    • main.ts
    • styles.css
  • README.md
  • package.json

A nested role="tree" → treeitem → group → treeitem widget (file explorers, nav trees, category pickers). Roving-tabindex focus management (DOM focus rides the treeitem), full keyboard interaction, RTL arrow mirroring, and aria-level / aria-setsize / aria-posinset wiring.

Selection and expansion are two independent models: value (selected nodes) and expanded (open nodes). Expansion is always multi; only value honours multiple.

Both models are readonly T[] over the node value type, which ForTree<T = string> infers from [(value)] / [(expanded)]. ForTable uses the same shape for its selected and open rows. Node identity is resolved by compareWith, which defaults to ===; bind [compareWith]="(a, b) => a.id === b.id" when your nodes are objects you re-create (a descendantsOf that maps fresh objects is the case that needs it, because under === a fully-checked subtree reports aria-checked="false").

Anatomy

<ul forTree [(value)]="selected" [(expanded)]="expanded" aria-label="Files">
  <li forTreeItem value="src">
    <div forTreeItemLabel>
      <span forTreeItemToggle>▸</span>
      src
    </div>

    <!-- rendered only while the node is expanded -->
    <ul forTreeGroup>
      <li forTreeItem value="main.ts">
        <div forTreeItemLabel>main.ts</div>
      </li>
    </ul>
  </li>
</ul>

Mounting is the consumer's responsibility: wrap [forTreeGroup] in @if (expanded().includes(node.id)) so a collapsed parent drops its subtree.

Trees are recursive, and the idiomatic Angular shape is a small recursive component for the node. This keeps dependency injection correct at every depth: each node component nests its element injector under its enclosing [forTreeGroup], so [forTreeItem] resolves the right level / container automatically.

Why not ngTemplateOutlet? A single recursive <ng-template> instantiated with [ngTemplateOutlet] resolves dependency injection from where the template is declared, not where it is inserted. A nested [forTreeItem] would then inject the root tree as its container instead of its enclosing [forTreeGroup], breaking aria-level and visible-order navigation. A recursive component avoids this. If you must use ngTemplateOutlet, pass an explicit [ngTemplateOutletInjector] captured at each insertion point.

In selectionMode="checkbox", place a checkbox surface inside the label:

<div forTreeItemLabel>
  <span forTreeItemToggle>▸</span>
  <span forTreeItemCheckbox>
    <span forTreeItemCheckboxIndicator>✓</span>
  </span>
  src
</div>

Examples

Cascading checkboxes

selectionMode='checkbox' switches each treeitem from aria-selected to aria-checked and lets every node toggle independently. cascade plus a descendantsOf descriptor propagates checks to all descendants (even collapsed ones) and surfaces aria-checked='mixed' on partially-checked parents.

  • Engineering
    • Frontend
      • Angular
      • React
      • Vue

Filter picker

Type part of a category name: the tree narrows to the matches, expands their ancestors to reveal them and highlights the matched text, while the cascade checkboxes keep working. The library filters nothing; Filtering is the three-step recipe, with the expandToReveal helper that computes which ancestors to open.

  • Engineering

Drag & drop reordering

[forTreeNodeDrag] on the root adds pointer and keyboard reordering and re-parenting; the ⠿ grip is an optional [forTreeNodeDragHandle]. The library never mutates your data, so apply the pure moveTreeNode helper in (nodeDrop). On lift the dragged subtree collapses, and its descendants are never offered as drop positions even when it is re-expanded mid-drag, so a node cannot be dropped into its own descendant.

  • Work
    • Roadmap.md
    • Budget.xlsx
    • Designs
      • logo.svg
      • hero.png
  • Personal
    • Recipes.md
    • Trip.pdf
  • Inbox.txt

Virtualized (12,300 nodes)

For huge trees, add forTreeVirtualized with [totalCount] to switch ForTree to the activedescendant model over a consumer-owned virtual window. We flatten the expanded tree to a linear list, feed its length to injectVirtualizer, and render only the visible slice. Each [forTreeItem] gets its absolute [itemIndex] plus level / setSize / posInSet so ARIA stays correct.

Multi select

<ul forTree multiple [(value)]="selected" [(expanded)]="expanded" aria-label="Files">
  ...
</ul>

In multi mode Space toggles the focused node; Shift+ArrowUp/Down extends; Shift+Space selects the contiguous range from the anchor; Ctrl/Cmd+A selects every visible enabled node (or deselects them when all are already selected, leaving selected disabled or hidden nodes selected).

Checkbox selection

selectionMode="checkbox" switches each treeitem to aria-checked (instead of aria-selected) and makes every node toggle independently, so multiple is not required: the tree reports aria-multiselectable="true" either way, and an inherited selectionFollowsFocus default leaves the checked set alone. Place [forTreeItemCheckbox] and [forTreeItemCheckboxIndicator] inside the label for a visible checkbox surface.

import {
  ForTree,
  ForTreeGroup,
  ForTreeItem,
  ForTreeItemCheckbox,
  ForTreeItemCheckboxIndicator,
  ForTreeItemLabel,
  ForTreeItemToggle,
} from 'forty-cdk/tree';

@Component({
  selector: 'app-tree-node',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ForTreeItem,
    ForTreeItemLabel,
    ForTreeItemToggle,
    ForTreeGroup,
    ForTreeItemCheckbox,
    ForTreeItemCheckboxIndicator,
    TreeNode,
  ],
  host: { style: 'display: contents' },
  template: `
    <li forTreeItem [value]="node().id">
      <div forTreeItemLabel>
        @if (node().children?.length) {
          <span forTreeItemToggle>▸</span>
        }
        <span forTreeItemCheckbox>
          <span forTreeItemCheckboxIndicator>✓</span>
        </span>
        {{ node().name }}
      </div>

      @if (node().children?.length && expanded().includes(node().id)) {
        <ul forTreeGroup>
          @for (child of node().children ?? []; track child.id) {
            <app-tree-node [node]="child" [expanded]="expanded()" />
          }
        </ul>
      }
    </li>
  `,
})
export class TreeNode {
  readonly node = input.required<Node>();
  readonly expanded = input.required<readonly string[]>();
}

@Component({
  selector: 'app-categories',
  imports: [ForTree, TreeNode],
  template: `
    <ul
      forTree
      selectionMode="checkbox"
      [(value)]="selected"
      [(expanded)]="expanded"
      aria-label="Categories"
    >
      @for (n of roots; track n.id) {
        <app-tree-node [node]="n" [expanded]="expanded()" />
      }
    </ul>
  `,
})
export class Categories {
  readonly selected = signal<readonly string[]>([]);
  readonly expanded = signal<readonly string[]>([]);
  readonly roots: Node[] = [
    { id: 'a', name: 'Alpha' },
    { id: 'b', name: 'Beta', children: [{ id: 'b1', name: 'Beta 1' }] },
  ];
}

Cascade selection

Add cascade and [descendantsOf] to enable tri-state propagation. Checking a parent selects it and all its descendants atomically (including collapsed / unmounted ones), and a parent derives aria-checked="mixed" / data-checked="mixed" when only some descendants are checked. Toggling a parent follows the descendants it can write: when all of them are checked it clears its subtree, otherwise it checks it. A parent's own id in [(value)] tracks its descendants: checking the last unchecked child adds it, and unchecking any child removes it, so a submitted value never carries a partly deselected category. With multiple, Shift+Arrow, Shift+Space and Ctrl/Cmd+A cascade the same way: each node they toggle brings its subtree along. The one exception is a virtualized tree, where an ancestor whose row is outside the rendered window is left as it is; there, derive the submitted categories from checkState() or from descendantsOf instead of trusting a parent's own entry (see Intentional limitations). The descendantsOf function must return every selectable descendant id of the given node (not just direct children).

A disabled node keeps its checked state through every cascade. A parent press, Shift+Arrow, Shift+Space and Ctrl/Cmd+A write only the enabled part of each subtree, so a disabled descendant stays checked or unchecked as it was. It still counts toward its ancestors: after a check, a parent whose disabled child is unchecked reads mixed and stays out of [(value)], and the next toggle clears what the check wrote. The tree knows a node is disabled only while it is mounted, so a disabled node inside a collapsed subtree is still checked or cleared with it. To protect it there too, leave it out of descendantsOf, which also stops it counting toward its ancestors.

@Component({
  selector: 'app-categories',
  imports: [ForTree, TreeNode],
  template: `
    <ul
      forTree
      selectionMode="checkbox"
      cascade
      [descendantsOf]="descendantsFn"
      [(value)]="selected"
      [(expanded)]="expanded"
      aria-label="Categories"
    >
      @for (n of roots; track n.id) {
        <app-tree-node [node]="n" [expanded]="expanded()" />
      }
    </ul>
  `,
})
export class Categories {
  readonly selected = signal<readonly string[]>([]);
  readonly expanded = signal<readonly string[]>([]);
  readonly roots: Node[] = [
    {
      id: 'fruits',
      name: 'Fruits',
      children: [
        { id: 'apple', name: 'Apple' },
        { id: 'pear', name: 'Pear' },
      ],
    },
  ];

  readonly descendantsFn = (id: string): readonly string[] => {
    const flatten = (nodes: Node[]): string[] =>
      nodes.flatMap((n) => [n.id, ...flatten(n.children ?? [])]);
    const find = (nodes: Node[]): Node | undefined =>
      nodes.find((n) => n.id === id) ?? nodes.flatMap((n) => find(n.children ?? [])).find(Boolean);
    const node = find(this.roots);
    return node?.children ? flatten(node.children) : [];
  };
}

Structural nodes

A group header is not an option: it organises the list and is worth navigating to, but there is no checkbox to act on. Set [selectable]="false" on it. The node keeps its place in the hierarchy: it retains aria-level / aria-setsize / aria-posinset and aria-expanded from its toggle, and arrow / Home / End / typeahead reach it. It also drops out of the selection contract: no aria-checked (nor aria-selected in 'highlight' mode), no data-checked, Space and Enter change nothing, and the value never enters [(value)].

It is orthogonal to disabled, which is the wrong lever here: that one announces the node as an unavailable option and takes it out of navigation, so a screen-reader user never learns which group an option belongs to.

Leave [forTreeItemCheckbox] off a structural node. It is the interactive half of the checkbox anatomy, so inside one it paints a box whose click selects nothing, and in dev mode each such click warns FORCDK-TREE-006.

<li forTreeItem value="colors" [selectable]="false">
  <div forTreeItemLabel>
    <span forTreeItemToggle>▸</span>
    <span>Colors</span>
  </div>

  <!-- rendered only while the node is expanded -->
  <ul forTreeGroup>
    <li forTreeItem value="red">
      <div forTreeItemLabel>
        <span forTreeItemCheckbox><span forTreeItemCheckboxIndicator>✓</span></span>
        Red
      </div>
    </li>
  </ul>
</li>

Under cascade, a non-selectable node is skipped when an ancestor collects its descendants: it neither enters the checked set nor counts toward that ancestor's 'mixed'. Its own descendants still cascade normally. The tree can only apply that to mounted nodes, so descendantsOf keeps its contract: return the selectable descendant values, leaving out any structural node in a collapsed subtree.

The structural node still derives its own group's roll-up. To show it on the header, read checkState() ('true', 'false' or 'mixed') off the node's forTreeItem export. That gives you a styling hook with no click behind it:

<li forTreeItem #colors="forTreeItem" value="colors" [selectable]="false">
  <div forTreeItemLabel [attr.data-rollup]="colors.checkState()">
    <span forTreeItemToggle>▸</span>
    <span>Colors</span>
  </div>
</li>

Filtering

forty-cdk ships no filtering machinery, so matching stays consumer-owned. The library exports one pure helper, expandToReveal, that translates the matched set into the ancestor values you need to expand so every match becomes visible.

Three-step recipe:

  1. Filter your own data and re-render. Derive a filtered node list with computed() and drive the tree's @for off that signal. The library adds no filtering engine, empty-state pieces, or snapshot logic.
  2. Expand ancestors with expandToReveal. Call expandToReveal(matches, ancestorsOf) with the nodes that matched the query, not with every node left in the filtered tree, to get the unique ancestor values [(expanded)] must hold. The helper is pure: it has no Angular reactivity, no DOM, and no side effects.
  3. Highlight matched text with consumer CSS. Wrap matched text in a <mark> element or apply a .match class while rendering filtered labels. No new data attribute is emitted by the library.
import { linkedSignal } from '@angular/core';
import { expandToReveal } from 'forty-cdk/tree';

readonly query = signal('');
readonly filtered = computed(() => filterNodes(this.roots, this.query()));

readonly expanded = linkedSignal<string, readonly string[]>({
  source: this.query,
  computation: (query) =>
    query.trim()
      ? expandToReveal(collectMatchIds(this.roots, query), this.ancestorsOf)
      : DEFAULT_EXPANDED,
});

collectMatchIds = (roots: readonly Node[], query: string): Set<string> => { /* the ids whose label matches, none for an empty query */ };
ancestorsOf = (id: string): readonly string[] => { /* walk roots, return the path */ };

The expansion is keyed on the query. Each new query replaces it with the ancestors of that query's matches, and an empty query restores DEFAULT_EXPANDED, the expansion the tree starts from. Deriving it from every node in filtered() instead opens the whole tree whenever the query is empty, because filterNodes then returns every root and every parent is an ancestor of something. Expand and collapse through [(expanded)] hold until the query changes. linkedSignal keeps the derivation out of an effect(), so no state is written inside one.

expandToReveal accepts any Iterable<T> (array, Set, generator) of node values. Root-level matches contribute nothing, because a root has no ancestors to expand.

Scoped defaults

provideForTreeDefaults configures tree defaults for an injector subtree, either at the application root or in any component's providers array. Partial overrides inherit unspecified keys from the parent scope (or the library fallbacks at the root).

KeyLibrary fallbackMeaning
selectionFollowsFocusfalseSingle mode only: whether every keyboard focus move (arrow navigation, entering a child, leaving to the parent, a typeahead match) also selects the focused node, for trees that don't set selectionFollowsFocus themselves.
dragAnnounceLift"Picked up <label>. Use arrow keys to move, Space to drop, Escape to cancel."Builds the [forTreeNodeDrag] announcement when a node is picked up. Receives the node's label and returns the string.
dragAnnounceMove"<label>: under <parentLabel>, position <position> of <total>."Builds the announcement on each intermediate move while a node is lifted. Receives label, parentLabel (null at the root, where the fallback says at root), the 1-based position and total (null in a collapsed parent, where the fallback leaves the total out), and returns the string.
dragAnnounceDrop"Dropped <label> under <parentLabel>, position <position> of <total>."Builds the announcement when a node is committed to its new position. Receives the same arguments as dragAnnounceMove and returns the string.
dragAnnounceCancel"Cancelled. <label> returned to its original position."Builds the announcement when a lift is cancelled and the node returns to its origin. Receives label and returns the string.
dragAnnounceInvalid"Cannot drop <label> here."Builds the announcement when a [canDrop] veto rejects the attempted drop. Receives label and returns the string.

Per-instance inputs always win over the scope defaults. selectionFollowsFocus only applies to single-select trees, so a multiple or selectionMode="checkbox" tree in the same scope ignores the default and keeps its checked set while the user navigates. A virtualized tree does not inherit it either: selection cannot follow an aria-activedescendant move that resolves off-window. Only a [selectionFollowsFocus] bound on a virtualized single-select tree itself is rejected, by a dev-mode error from the first keyboard move. The drag builders have no per-instance input; Localizing drag announcements describes the label / parentLabel text they receive.

import { type ApplicationConfig } from '@angular/core';
import { provideForTreeDefaults } from 'forty-cdk/defaults';

export const appConfig: ApplicationConfig = {
  providers: [
    provideForTreeDefaults({
      selectionFollowsFocus: true,
      dragAnnounceLift: (label) =>
        `${label} levantado. Usa las flechas para mover, Espacio para soltar, Escape para cancelar.`,
      dragAnnounceMove: (label, parentLabel, position, total) =>
        `${label}: ${parentLabel ? `dentro de ${parentLabel}, ` : 'en la raíz, '}posición ${position}${total === null ? '' : ` de ${total}`}.`,
      dragAnnounceDrop: (label, parentLabel, position, total) =>
        `${label} soltado ${parentLabel ? `dentro de ${parentLabel}, ` : 'en la raíz, '}posición ${position}${total === null ? '' : ` de ${total}`}.`,
      dragAnnounceCancel: (label) => `Cancelado. ${label} vuelve a su posición original.`,
      dragAnnounceInvalid: (label) => `No se puede soltar ${label} aquí.`,
    }),
  ],
};

Virtualization

For very large trees (thousands of nodes) add [forTreeVirtualized] to the [forTree] element and bind its [totalCount] to switch to an activedescendant focus model over a consumer-owned virtualized window. ForTreeVirtualized is exported from forty-cdk/tree; add it to your component's imports next to ForTree. A tree without the directive never bundles the virtualized navigation engine.

Render that window with injectVirtualizer, not the *forVirtualFor ergonomic layer. *forVirtualFor writes the flat aria-setsize / aria-posinset on each row root on every render, which overwrites the per-level values [forTreeItem] binds from [setSize] / [posInSet] once the window moves.

Opt-in API

ForTreeVirtualized

Placed on the same element as [forTree] (exportAs: 'forTreeVirtualized'). ForTree keeps a read-only totalCount signal that reports the count bound here.

APITypeDescription
totalCount
input
Total flattened node count. Setting this switches the tree to the activedescendant focus model. Leave unset for roving-tabindex.
visibleRange
input
Inclusive-exclusive [start, end) index range of the currently rendered nodes. Provided by injectVirtualizer.
dataVersion
input
Bind any value that changes when the flattened list is re-sorted or refreshed without its length changing, so navigation never lands on a stale off-window entry. Leave unset when the list only ever changes length.
scrollToIndex
output
Emitted when keyboard navigation reaches a node outside the rendered window. Forward to injectVirtualizer's scrollToIndex.
invalidateSnapshot()
method
The imperative twin of dataVersion: call it after a same-length refresh you cannot express through the input. No-op while totalCount is unset.

ForTreeItem additions (virtualized path only)

APITypeDescription
itemIndex
input
Zero-based absolute index in the flattened node list. Required in the virtualized path. Leave unset (default null) outside the virtualized path.
level
input
Tree depth of this node (1-based). Overrides the container-derived aria-level in the virtualized path.
setSize
input
Total siblings at this node's level. Overrides the container-derived aria-setsize in the virtualized path.
posInSet
input
1-based position among siblings (matches aria-posinset). Overrides the container-derived value in the virtualized path.

Naming note: [posInSet] is the per-level aria-posinset (position among siblings at this level, 1-based). It is not the absolute flat index, which is [itemIndex]. This matches the ARIA attribute name and is intentionally different from how some other APIs name it.

Focus-model switch

ModeTree host tabindexItem tabindexFocus mechanism
Standard (no totalCount)none0 on one itemDOM focus rides the item (roving)
Virtualized (totalCount is set)0-1 alwaysaria-activedescendant on the host
  1. Consumer flattens their visible tree into a flat list, computing level, setSize, and posInSet for each node (using the true sibling totals: off-window siblings contribute their real counts because the consumer knows them). A node's itemIndex is its position in that whole flat list, which is the index the virtualizer reports for its row.
  2. injectVirtualizer({ count: flatCount, estimateSize, scrollElement, getItemKey: (i) => flat()[i].value }) drives the render window. Keying rows by node value keeps a row bound to one node when an expand or collapse shifts the list.
  3. [forTreeVirtualized] on the tree host emits (scrollToIndex) when keyboard navigation needs a node outside the window; the consumer forwards the index to v.scrollToIndex(idx, { align: 'auto' }).
  4. Once the target node mounts (carrying the requested [itemIndex]), the bridge effect resolves the pending activedescendant.
  5. ArrowLeft and ArrowRight land where they do in the standard tree: the parent, or the first enabled child. When the rows between the active node and that target have never been rendered, the tree emits (scrollToIndex) for them and continues once they mount, so it never skips past an unknown row.
  6. aria-activedescendant follows the active node by [value], not by row, so a row that comes to show another node never stays active. When a write to [(expanded)] collapses the active node away, the next key, or focus re-entering the tree, resumes on its nearest visible ancestor.
  7. Focus entering the tree with no active node seeds the node it was on before that node left the window, else the first selected node the window has rendered at least once, else the first rendered enabled node. Seeding an off-window node emits (scrollToIndex), and aria-activedescendant settles once it mounts.

Consumer example

import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  computed,
  signal,
  viewChild,
} from '@angular/core';
import {
  ForTree,
  ForTreeItem,
  ForTreeItemLabel,
  ForTreeItemToggle,
  ForTreeVirtualized,
} from 'forty-cdk/tree';
import { injectVirtualizer } from 'forty-cdk/virtualization';

interface TreeNode {
  value: string;
  label: string;
  children?: TreeNode[];
}

interface FlatNode {
  value: string;
  label: string;
  level: number;
  setSize: number;
  posInSet: number;
  expandable: boolean;
}

function flatten(nodes: TreeNode[], expanded: ReadonlySet<string>, level = 1): FlatNode[] {
  const result: FlatNode[] = [];
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i]!;
    result.push({
      value: node.value,
      label: node.label,
      level,
      setSize: nodes.length,
      posInSet: i + 1,
      expandable: !!node.children?.length,
    });
    if (node.children?.length && expanded.has(node.value)) {
      result.push(...flatten(node.children, expanded, level + 1));
    }
  }
  return result;
}

@Component({
  selector: 'app-virtual-tree',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ForTree, ForTreeItem, ForTreeItemLabel, ForTreeItemToggle, ForTreeVirtualized],
  template: `
    <ul
      forTree
      forTreeVirtualized
      #scroll
      aria-label="Files"
      [(value)]="selected"
      [(expanded)]="expanded"
      [totalCount]="flat().length"
      [visibleRange]="v.range()"
      (scrollToIndex)="v.scrollToIndex($event, { align: 'auto' })"
      style="overflow: auto; max-height: 400px; position: relative;"
    >
      <div [style.height.px]="v.totalSize()" style="position: relative">
        @for (vi of v.virtualItems(); track vi.key) {
          <li
            forTreeItem
            [value]="flat()[vi.index]!.value"
            [level]="flat()[vi.index]!.level"
            [setSize]="flat()[vi.index]!.setSize"
            [posInSet]="flat()[vi.index]!.posInSet"
            [itemIndex]="vi.index"
            [style.transform]="'translateY(' + vi.start + 'px)'"
            style="position: absolute; left: 0; right: 0;"
          >
            @if (flat()[vi.index]!.expandable) {
              <span forTreeItemToggle>▸</span>
            }
            <div forTreeItemLabel>{{ flat()[vi.index]!.label }}</div>
          </li>
        }
      </div>
    </ul>
  `,
})
export class VirtualTree {
  readonly selected = signal<readonly string[]>([]);
  readonly expanded = signal<readonly string[]>([]);

  readonly roots: TreeNode[] = [/* large tree data */];

  readonly flat = computed(() => flatten(this.roots, new Set(this.expanded())));

  private readonly scrollRef = viewChild<ElementRef<HTMLElement>>('scroll');
  private readonly scrollElement = computed(() => this.scrollRef()?.nativeElement ?? null);

  readonly v = injectVirtualizer({
    count: computed(() => this.flat().length),
    estimateSize: () => 32,
    scrollElement: this.scrollElement,
    getItemKey: (index) => this.flat()[index]!.value,
  });
}

Intentional limitations

The following behaviors are unavailable or bounded in the virtualized path and are documented intentional limitations (same as listbox/select virtualization):

  • Multi-select range modifiers (Shift+ArrowUp/Down, Shift+Space, Ctrl/Cmd+A) are unsupported: pressing one on a virtualized [multiple] tree throws in dev mode (a no-op in production) rather than silently degrading. Range selection requires knowing the full list of enabled nodes in the range, which is not available when the list is partially unmounted. Use selectionMode="checkbox" (each node toggles independently, so no range is needed) for multi-select over large trees.
  • Typeahead reaches only positions the window has rendered at least once. The search runs over the persisted position snapshot rather than the live nodes, so a node the virtualizer has since unmounted is still reachable. The match moves aria-activedescendant to it and emits (scrollToIndex) so your virtualizer brings it back. A position the window has never rendered carries no text the library can match: the keystroke is consumed, the buffer grows, and nothing moves. The shape that triggers it is a freshly-rendered [totalCount] tree where the user types before scrolling, and a [dataVersion] bump or ForTreeVirtualized.invalidateSnapshot() narrows the reachable set back to the current window. Arrow / Home / End navigation reaches every position regardless (it walks absolute indices, not text), so that is the workaround for a target the user cannot type their way to; rendering a larger window widens the reachable set.
  • Cascade reconciles only the ancestors in the rendered window. A parent's own entry in [(value)] follows its descendants through the rows the tree can see, so when a fully checked parent has scrolled out of the window and the user unchecks one of its children, the parent stays in the value while it reads mixed once scrolled back. Submit the categories you derive from checkState() or descendantsOf, not a parent's own entry.
  • Drag & drop is unsupported. [forTreeNodeDrag] on a virtualized tree starts no drag, by pointer or by key, and warns once in dev mode (FORCDK-TREE-007): a drop has to resolve its new parent and its position among that parent's children, and the rendered window holds neither a parent scrolled out of it nor the siblings outside it. The lift key keeps its meaning in the tree, so Shift+Enter activates the active node.
  • * (expand-all-siblings) is dropped: the key is consumed, expands nothing and does not enter the typeahead buffer. Expanding the siblings requires knowing all of them at the focused node's level, including those outside the window.

Drag & drop

Add [forTreeNodeDrag] on the same element as [forTree] to enable pointer and keyboard drag reordering and re-parenting.

Scope: [forTreeNodeDrag] targets the standard roving-tabindex tree. A virtualized tree ([forTreeVirtualized] with [totalCount] set) is left untouched, since a drop cannot resolve a parent or a sibling position outside the rendered window (see Intentional limitations).

Pieces

ClassSelectorDescription
ForTreeNodeDrag[forTreeNodeDrag]Root coordinator. Apply on the same element as [forTree].
ForTreeNodeDragHandle[forTreeNodeDragHandle]Optional grab-area constraint inside an item. When present, pointer drags start only from within it. Carries touch-action: none while its node can be dragged, so a touch drag on it is not taken by the page's scrolling, and none while [forTreeNodeDrag], the tree or the node is disabled, or while the tree is virtualized.

Inputs / outputs

APITypeDescription
disabled
input
Disables all drag interactions. Default false.
canDrop
input
Optional veto callback. Return false to reject a specific move. When omitted, all drops are accepted.
nodeDrop
output
Emitted once per committed move. Apply moveTreeNode in the handler to update your data.

A non-string tree must bind [canDrop]

ForTreeNodeDrag<T = string> is generic over the same node value type as ForTree. Unlike the root, which infers T from [(value)] / [(expanded)], it has no input that carries T on its own except [canDrop]. So if your node values are not string, bind it, typed at the node value:

readonly canDrop = (event: ForTreeDragDropEvent<FileNode>): boolean => true;
<ul forTree forTreeNodeDrag [(value)]="picked" [canDrop]="canDrop" (nodeDrop)="onDrop($event)"></ul>

A callback that vetoes nothing is enough, because its only job here is to carry the inference.

Read the diagnostic you get without it carefully, because the obvious fix is the wrong one. With no [canDrop], T stays at its string default, so (nodeDrop) reports ForTreeDragDropEvent<string> while the runtime hands you the node value you actually bound. A handler typed at your real node type fails to compile:

TS2345: Argument of type 'ForTreeDragDropEvent<string>' is not assignable to
        parameter of type 'ForTreeDragDropEvent<FileNode>'.

The error points at your handler, not at the missing input. Retyping the handler to string to satisfy it is what turns a compile error into a silent one: moveTreeNode then infers its own V as string, your trackBy returns a string id, and the comparison against the object the event really carries never matches, so the helper returns your roots unchanged. The drag completes, the announcement fires, and nothing moves.

Annotating a viewChild / @ViewChild reference (ForTreeNodeDrag<FileNode>) recovers T for reading dropIndicator from TypeScript, but it cannot retype a template binding, so [canDrop] is the only channel that fixes (nodeDrop).

Keyboard interaction

KeyBehavior while not liftedBehavior while lifted
Shift+EnterLifts the focused node.—
ArrowDownNormal tree navigation.Moves the insertion point one row down.
ArrowUpNormal tree navigation.Moves the insertion point one row up.
Home / EndNormal tree navigation.Moves the insertion point to the first / last row. Focus stays on the lifted node.
ArrowRightNormal expand / enter.Deepens the target level by 1 (LTR; reversed under RTL).
ArrowLeftNormal collapse / leave.Shallows the target level by 1 (LTR; reversed under RTL).
Space / EnterNormal select / activate.Drops the node at the current resolved position. Focus follows the node, or lands on its new parent when that parent is collapsed.
Escape—Cancels the drag; the node is returned to its original position.
TabNormal focus leave.Cancels the drag.
Any other keyNormal tree behavior.Consumed, so *, typeahead, Ctrl/Cmd+A and your own item key handlers cannot move focus, select or expand nodes mid-drag. Ctrl / Cmd / Alt chords and function keys keep their browser meaning.

A press on another node cancels a keyboard drag, restoring the lifted node's expansion, so a drag that follows it is an ordinary pointer drag. A press on the lifted node itself starts no pointer drag.

Ctrl+Space lifts too where the page receives it, but don't make it the only key you document: macOS takes Cmd+Space for Spotlight and Ctrl+Space for switching input sources, and many IMEs on Windows and Linux toggle on Ctrl+Space. To use another key, set liftKey in provideForDragDropDefaults and add the result to a providers array; it applies to every reorder coordinator in that scope. A key press that belongs to an IME composition never lifts.

import { provideForDragDropDefaults } from 'forty-cdk/defaults';

export const reorderLiftKey = provideForDragDropDefaults({
  liftKey: (event) => event.key === 'Enter' && event.ctrlKey,
});

A pointer drag picks the depth from how far the pointer has moved sideways since the press. The node keeps its own depth until the pointer has travelled half an indent step; from there, each step toward the inline end deepens the drop by one level and each step toward the inline start raises it by one, so under dir="rtl" moving left deepens. The step is the indent between the [forTreeItem] hosts of two visible depths, and 24px while only one depth is visible or the hosts carry no indent of their own. The depth then stays within what the insertion point allows: no shallower than the row below it and at most one level deeper than the row above, so a pointer can drop into a collapsed parent, as ArrowRight does from the keyboard.

During a pointer drag, Escape cancels the drag and is consumed, so an enclosing dialog or popover stays open. A drop made while focus was on the dragged node, by keyboard or by pointer, moves focus with the node, or onto its new parent when that parent is collapsed; a pointer drop made while focus was elsewhere leaves it there.

Minimal example

import { ChangeDetectionStrategy, Component, input, signal } from '@angular/core';
import {
  ForTree,
  type ForTreeDragDropEvent,
  ForTreeGroup,
  ForTreeItem,
  ForTreeItemLabel,
  ForTreeItemToggle,
  ForTreeNodeDrag,
  ForTreeNodeDragHandle,
  moveTreeNode,
} from 'forty-cdk/tree';

interface Node {
  id: string;
  name: string;
  children?: Node[];
}

@Component({
  selector: 'app-tree-node',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ForTreeItem,
    ForTreeItemLabel,
    ForTreeItemToggle,
    ForTreeGroup,
    ForTreeNodeDragHandle,
    TreeNode,
  ],
  host: { style: 'display: contents' },
  template: `
    <li forTreeItem [value]="node().id">
      <div forTreeItemLabel>
        <span forTreeNodeDragHandle aria-hidden="true">⠿</span>
        @if (node().children?.length) {
          <span forTreeItemToggle>▸</span>
        }
        {{ node().name }}
      </div>
      @if (node().children?.length && expanded().includes(node().id)) {
        <ul forTreeGroup>
          @for (child of node().children ?? []; track child.id) {
            <app-tree-node [node]="child" [expanded]="expanded()" />
          }
        </ul>
      }
    </li>
  `,
})
export class TreeNode {
  readonly node = input.required<Node>();
  readonly expanded = input.required<readonly string[]>();
}

@Component({
  selector: 'app-files',
  imports: [ForTree, ForTreeNodeDrag, TreeNode],
  template: `
    <ul
      forTree
      forTreeNodeDrag
      [(value)]="selected"
      [(expanded)]="expanded"
      [canDrop]="canDrop"
      (nodeDrop)="onDrop($event)"
      aria-label="File system"
    >
      @for (n of roots(); track n.id) {
        <app-tree-node [node]="n" [expanded]="expanded()" />
      }
    </ul>
  `,
})
export class Files {
  readonly selected = signal<readonly string[]>([]);
  readonly expanded = signal<readonly string[]>([]);
  readonly roots = signal<Node[]>([
    {
      id: 'documents',
      name: 'Documents',
      children: [
        { id: 'resume', name: 'Resume' },
        { id: 'projects', name: 'Projects', children: [{ id: 'alpha', name: 'Alpha' }] },
      ],
    },
    { id: 'readme', name: 'Readme' },
  ]);

  readonly folders: ReadonlySet<string> = new Set(['documents', 'projects']);

  readonly canDrop = (event: ForTreeDragDropEvent): boolean => {
    return event.newParent === null || this.folders.has(event.newParent);
  };

  onDrop(event: ForTreeDragDropEvent): void {
    this.roots.update((r) =>
      moveTreeNode(r, {
        event,
        trackBy: (n) => n.id,
        children: (n) => n.children,
        withChildren: (n, children) => ({ ...n, children: children as Node[] }),
      }),
    );
  }
}

Data attributes on [forTreeNodeDrag]

AttributeValuesWhen present
data-dragging"" (empty)A drag session is live (pointer or keyboard).
data-drop-target"" (empty)The resolved position passes [canDrop].
--for-tree-drop-levelinteger 1–NThe resolved depth of the current target.

Drop indicator

While a drag is live, the single [forTreeItem] the lifted node would land beside reflects data-drop-position so you can draw an indented insertion line. Exactly one visible item carries it at a time; it is absent on every other row and whenever the tree is idle. It tracks every pointer move and every Arrow step (in both LTR and RTL) and clears on drop / cancel / Escape / Tab.

PieceAttributeValues
[forTreeItem]data-drop-position"before" | "after" (the line sits above / below the row)
[forTreeItem]data-drop-invalid"" (empty), on the anchor row while [canDrop] refuses the position

When [canDrop] refuses the resolved position, the anchor row keeps data-drop-position and also carries data-drop-invalid, so you can draw a "not allowed" line instead of hiding it, and the move is announced with dragAnnounceInvalid rather than as a position. The root's data-drop-target is absent at the same time.

Pair it with the root's --for-tree-drop-level (the resolved depth) to indent the line to the target level. The anchor row is already indented by its own nesting, so offset the line by the difference between the two levels rather than by the drop level alone. Publish each row's level from the item's exported level(), and draw the line on a positioned label so it lands on the anchor row:

<li
  forTreeItem
  #item="forTreeItem"
  class="tree-item"
  [value]="node().id"
  [style.--tree-node-level]="item.level()"
>
  <div forTreeItemLabel class="tree-label">…</div>
</li>
.tree-label {
  position: relative;
}
.tree-item[data-drop-position] > .tree-label::after {
  content: '';
  position: absolute;
  inset-inline-start: calc((var(--for-tree-drop-level, 1) - var(--tree-node-level, 1)) * 1rem);
  inset-inline-end: 0;
  height: 2px;
  background: var(--accent);
}
.tree-item[data-drop-position='before'] > .tree-label::after {
  top: 0;
}
.tree-item[data-drop-position='after'] > .tree-label::after {
  bottom: 0;
}
.tree-item[data-drop-invalid] > .tree-label::after {
  background: var(--danger);
}

1rem stands for the indent each nested group adds. inset-inline-start follows the writing direction, so the line indents from the right under dir="rtl".

Advanced consumers can read the same resolved position programmatically: [forTreeNodeDrag] exposes a read-only dropIndicator: Signal<ForTreeDropIndicator<T> | null> ({ anchor, position, level, valid }, null when idle). Injecting it through ForTreeNodeDragContext reads the same signal at ForTreeDropIndicator<unknown>, since a token cannot carry the node value type.

On lift the dragged node's subtree is collapsed (and restored on drop / cancel). This keeps the drop geometry tractable. Independently of it, the lifted node's descendants are never offered as drop positions, so a re-expansion during the drag (a toggle click or a write to [(expanded)]) cannot let a node be dropped into its own descendant; [canDrop] adds consumer-defined vetoes on top.

Localizing drag announcements

While a drag is in flight, [forTreeNodeDrag] announces lift / move / drop / cancel / invalid-drop through an off-screen live region. The phrasing is English by default; override it per injector scope with provideForTreeDefaults so screen readers speak the consumer's language. position / total are 1-based, and parentLabel is null when the node lands at the root. Phrase the root-vs-parent distinction in your own language. total is null when the node lands in a collapsed parent: its children are not rendered, so the tree cannot count them, and the default phrasing leaves the total out.

The label and parentLabel a formatter receives are the node's [textValue] when it carries one, and the accessible text of its [forTreeItemLabel] otherwise. That is the same text typeahead matches against, so a node is announced by the name the user types to reach it, and aria-hidden decoration inside the label (a toggle caret, a checkbox glyph) is excluded from both.

The five dragAnnounce* builders are listed under Scoped defaults.

API

ForTree

PropertyTypeDescription
value
model
Two-way bindable. Selected node values. Single mode keeps 0 or 1; multi any number.
Default: []
expanded
model
Two-way bindable. Open (expanded) parent node values. Always multi.
Default: []
selected
Signal
Read-only single-select convenience view of value: the sole selected value, or null when none / many are selected.
Default: —
compareWith
input
Equality comparator for node values. Selection and expansion membership, cascade descendants, the range anchor, and drag-drop resolution all route through it.
Default: (a, b) => a === b
multiple
input
When true, multiple nodes can be selected.
Default: false
disabled
input
Disables the whole tree. Reflected as aria-disabled / data-disabled.
Default: —
orientation
input
Navigation axis. 'vertical' (ArrowUp/Down move; ArrowLeft/Right expand/collapse). Reflected as aria-orientation / data-orientation.
Default: 'vertical'
ariaLabel
input
Reactive accessible name, reflected as aria-label. Prefer native aria-labelledby when a visible label exists.
Default: null (and empty) emits no attribute
dir
input
Writing direction. null resolves the inherited ambient direction; an explicit value wins. Reflected to the host dir attribute when set or declared and mirrors the expand/collapse arrows in RTL.
Default: null
selectionFollowsFocus
input
Single-mode only. When true, every keyboard focus move (arrow navigation, entering a child, leaving to the parent, a typeahead match) also selects the focused node. Ignored under multiple or selectionMode="checkbox". A virtualized tree does not inherit the scope default.
Default: from provideForTreeDefaults
selectionMode
input
Selection presentation. 'highlight' uses aria-selected; 'checkbox' uses aria-checked and renders the checkbox anatomy (inherently multi-select).
Default: 'highlight'
cascade
input
Enables cascade selection in selectionMode="checkbox": checking / unchecking a node propagates to all descendants, and a parent reports aria-checked="mixed" when only some descendants are checked. Requires descendantsOf.
Default: false
descendantsOf
input
Returns the selectable descendant values of a node (excluding the node itself), disabled ones included: a cascade leaves a mounted disabled descendant as it is and counts it toward its ancestors. Required when cascade is true; the tree throws a [forty-cdk/tree] error otherwise.
Default: —
itemActivate
output
Emitted once per press on a node, before the selection is applied: a click on its [forTreeItemLabel] or [forTreeItemCheckbox], or Enter / Space on the focused node, virtualized or not. Carries the node value and the click / keydown as event, so its modifier keys are readable. preventDefault() skips the selection, so [(value)] is unchanged and (valueChange) does not fire, while focus still moves to the node. It fires on a [selectable]="false" node too, where there is no selection to veto, and never on a disabled node.
Default: —
Data attributeValues
data-orientationvertical | horizontal
data-disabledpresent | absent

ForTreeItem

PropertyTypeDescription
value
input.required
The node's value. Must be unique within the tree.
Default: —
disabled
input
Disables this node: not selectable, skipped by keyboard navigation.
Default: —
selectable
input
Whether the node takes part in selection. false marks a structural node: it keeps navigation, typeahead and its ARIA position, but emits no selection state and never enters [(value)].
Default: true
textValue
input
Text override for the node's name, used by typeahead matching and by the drag announcements. Falls back to the [forTreeItemLabel]'s accessible text when empty, which excludes any aria-hidden subtree, so a nested [forTreeItemToggle] or [forTreeItemCheckbox] glyph contributes nothing.
Default: —
Data attributeValues
data-stateopen | closed (parent items only)
data-selectedpresent | absent
data-highlightedpresent | absent
data-disabledpresent | absent
data-checked"true" | "false" | "mixed" (checkbox mode only)

A [forTreeItem] emits data-state only when it is a parent (a [forTreeItemToggle] is registered inside it); leaves carry neither data-state nor aria-expanded. Expansion (data-state) and selection (data-selected) are independent hooks because a node can be both expandable and selected at once.

ForTreeItemToggle

Data attributeValues
data-stateopen | closed

ForTreeItemCheckbox

Data attributeValues
data-statechecked | unchecked | indeterminate
data-disabledpresent | absent

data-disabled mirrors the node's disabled state, whether it comes from the item's own [disabled] or the root's, so the box can share one disabled style with a standalone [forCheckbox].

ForTreeItemCheckboxIndicator

Data attributeValues
data-statechecked | unchecked | indeterminate

Keyboard

Vertical, LTR (mirrored for dir="rtl"):

KeyBehavior
ArrowDown / ArrowUpMove focus to the next / previous visible node (no wrap; collapsed subtrees are skipped).
ArrowRightClosed parent → expand (focus stays); open parent → focus its first enabled child (no-op when every child is disabled); leaf → no-op.
ArrowLeftOpen parent → collapse (focus stays); otherwise → focus the parent node; closed root → no-op.
Home / EndFirst / last visible node.
EnterActivate the focused node: emits (itemActivate), then selects it unless vetoed.
SpaceActivate like Enter. Single: select. Multi: toggle the focused node's selection.
*Expand every enabled sibling parent at the focused node's level; a disabled one stays closed.
type a characterTypeahead: focus the next visible node whose label starts with the buffer.
Shift+ArrowUp/DownMulti: move focus and toggle the new node's selection.
Shift+SpaceMulti: select the contiguous range from the anchor to the focused node.
Ctrl/Cmd+AMulti: select every visible enabled node (deselects them when all are already selected).

Under dir="rtl" the expand / collapse arrows swap: ArrowLeft expands and ArrowRight collapses.

With selectionMode="checkbox" and cascade, the three multi shortcuts toggle each node together with its subtree and keep every visible ancestor in step, exactly like a press on the node does.

Accessibility

Implements the WAI-ARIA Tree View pattern (APG Approach A, where DOM focus rides the treeitem).

  • Label the tree via the reactive [ariaLabel] input or a native aria-labelledby pointing at a visible heading.
  • data-state="open" | "closed" is reflected on parent nodes only (and on the toggle); leaves carry neither, matching aria-expanded.
  • data-selected (present / absent) reflects selection on every node. A node is simultaneously expandable and selectable, so expansion (data-state) and selection (data-selected) get separate hooks.
  • data-highlighted="" marks the current roving-tabindex node, or the node under the pointer while one is hovered, the same hook used across the listbox / menu / select primitives. Hover moves neither DOM focus nor the selection, the next arrow key takes the highlight back, and leaving the tree hands it back to the focused node, which keeps it after focus leaves the tree. In the virtualized path hover moves aria-activedescendant with it.
  • Exactly one node is tabbable at a time (the selected node, or the first enabled visible node, which is a child when the roots above it are disabled). Tab enters and leaves the whole tree in one stop.
  • The tab stop stays where the user was. When the active node is removed, collapsed away (through a toggle, the keyboard or a write to [(expanded)]) or disabled, the tab stop moves to the nearest visible enabled node before it, which is the collapsed ancestor on a collapse. If the node held focus when it left the DOM, focus moves there too; focus on a control outside the tree is left alone. A node disabled while it holds focus keeps the arrow keys, Home, End and typeahead. On it the expand / collapse arrows only move focus: they reach the parent or, on an open parent, the first child, and never expand or collapse it.
  • A [selectable]="false" node emits neither aria-checked nor aria-selected (and neither data-checked nor data-selected), so assistive tech announces a group header as a heading in the hierarchy rather than as an option the user can act on. It carries no aria-disabled and keeps its tab stop, its aria-level / aria-setsize / aria-posinset and its aria-expanded.
  • aria-multiselectable="true" is set on the tree under multiple and in selectionMode="checkbox", which is multi-select with or without multiple.
  • In selectionMode="checkbox" each treeitem emits aria-checked ("true" / "false") and no aria-selected; the [forTreeItemCheckbox] and [forTreeItemCheckboxIndicator] are aria-hidden / decorative, because the treeitem itself is the accessible checkbox. With cascade, a parent reports aria-checked="mixed" (and data-checked="mixed") when only some of its descendants are checked; the cascade reaches collapsed / unmounted descendants through the descendantsOf descriptor, so the tri-state is always correct even when children are not yet mounted.

Styling

forty-cdk ships no styles: put your own class on each piece and key your CSS off the data-* attributes listed under API, not off the for* selectors (Styling forty-cdk explains why).

.tree-toggle {
  display: inline-block;
  transition: transform 150ms;
}
.tree-toggle[data-state='open'] {
  transform: rotate(90deg);
}
.tree:is(:focus-within, :hover) .tree-item[data-highlighted] {
  outline: 2px solid Highlight;
}

Wrapping in a design system

Subclass the root and re-provide both of its tokens with useExisting pointing at the subclass, since Angular does not inherit a directive's providers: FOR_TREE_CONTEXT, and FOR_TREE_CONTAINER_CONTEXT, which every root-level [forTreeItem] registers through. Leaving out the second one throws FORCDK-TREE-002 from the first root-level item. Wrapping non-form roots walks the pattern.

import { Directive } from '@angular/core';
import { FOR_TREE_CONTAINER_CONTEXT, FOR_TREE_CONTEXT, ForTree } from 'forty-cdk/tree';

@Directive({
  selector: '[myTree]',
  exportAs: 'myTree',
  providers: [
    { provide: FOR_TREE_CONTEXT, useExisting: MyTree },
    { provide: FOR_TREE_CONTAINER_CONTEXT, useExisting: MyTree },
  ],
})
export class MyTree<T = string> extends ForTree<T> {}

To read the tree from a piece of your own, inject the token with the node value type: inject<ForTreeContext<string>>(FOR_TREE_CONTEXT). Without the type argument every node value reads as unknown.