forty-cdk
llms.txt

Utilities

Virtualization

A headless windowing core (injectVirtualizer) plus an ergonomic [forVirtualViewport] + *forVirtualFor layer that render only the visible slice of huge lists. Fixed or measured item sizes, horizontal lists, scroll-to-index, and an infinite-scroll detector. List primitives (Select, Combobox, Listbox, Tree, Table) compose it directly.

forty-cdk/virtualization

Scroll the list and watch the DOM: only the rows in view exist, each carrying its own data-index, while the sizer keeps the scrollbar honest.

Given a reactive item count, a size estimator, and a scroll container, the core returns the slice of items currently visible (plus overscan), the total scroll size, and imperative scroll/measure helpers. The consumer renders the items with their own @for and applies the position transform. This primitive owns no DOM. Backed internally by @tanstack/virtual-core. SSR-safe: off-browser it returns an empty window and the estimate-based total without touching document/window.

Ships from the forty-cdk/virtualization secondary entry point. Import every symbol below (injectVirtualizer, ForVirtualViewport, ForVirtualFor, injectInfiniteScroll) from forty-cdk/virtualization, not forty-cdk. This keeps @tanstack/virtual-core out of the bundle for apps and routes that don't virtualize.

This entry point imports no other primitive. The two adapters that compose one ship from their own specifiers: forty-cdk/table-virtualization ([forTableVirtualized], which also needs forty-cdk/table) and forty-cdk/virtual-reorder ([forVirtualReorder], which also needs forty-cdk/drag-drop).

Ergonomic layer

For the common "just virtualize this list" case, the optional Shape A layer wraps the manual wiring: [forVirtualViewport] owns the scroll container, the total-size sizer, and the windowing core, and *forVirtualFor renders the visible window with the position transform and aria-setsize / aria-posinset applied for you.

<div
  forVirtualViewport
  [virtualCount]="rows().length"
  [estimateSize]="44"
  role="list"
  aria-label="Rows"
  tabindex="0"
  style="height: 400px"
>
  <div *forVirtualFor="let row of rows(); let item = virtualItem" role="listitem">
    {{ row.label }}
  </div>
</div>
readonly rows = signal(Array.from({ length: 10000 }, (_, i) => ({ label: `Row ${i}` })));

The viewport forces overflow: auto on its host; give it a fixed size (e.g. height: 400px). orientation, overscan, and getItemKey are optional inputs on [forVirtualViewport]; set orientation / overscan before first render (they are read once when the viewport initializes). [estimateSize] and [getItemKey] apply whenever they change. [dir] sets the writing direction; left unset, the viewport follows the nearest ancestor dir attribute, then <html dir>, including a change at runtime. A horizontal viewport in RTL starts at its right edge and scrolls leftwards, with the rows laid out from that edge. The template context exposes row ($implicit), virtualItem, index, and count. Do not set position / transform on the row yourself, because the directive owns them.

Rows are keyed by index by default, so a sort or reorder that keeps the list length reuses each slot's DOM node for whichever item now sits there. Bind [getItemKey] (for example (index) => rows()[index].id) when a row holds state its node carries, such as an input's value, focus or an expanded detail: keys are recomputed whenever *forVirtualFor receives a new array or a different function is bound, so each row's node and its measured size move with its item.

*forVirtualFor writes the flat aria-setsize (the total count) and aria-posinset (index + 1) on each row root on every render, so it fits a flat list. Those attributes are read only on a role that supports them, so the row root needs one: role="listitem" inside a role="list" viewport as above, or option / row / treeitem / article in a matching container. On a role-less <div> assistive technology exposes no list and no count. The layer adds no role of its own.

Give the viewport a label and tabindex="0" too when its rows hold nothing focusable. Some browsers make a scroll container focusable on their own and others, Safari among them, do not, so without the Tab stop a keyboard user there cannot scroll the list, and an (endReached) list never loads its next page for them. A collection that binds its own positions, such as a tree whose [forTreeItem] binds [setSize] / [posInSet] per level, uses injectVirtualizer directly, as the Tree README's virtualized example does.

For full control (custom DOM, dynamic per-item measurement) use the headless injectVirtualizer core directly, documented below. Both layers scroll an element: the window or the document cannot be the scroll container.

Examples

Dynamic heights (measured)

When rows vary in height, drop to the headless injectVirtualizer core: it owns no DOM, so the consumer renders the spacer and the absolutely-positioned window. Each row carries [attr.data-index] and is fed to measureElement() in afterEveryRender, so estimates refine and jumping to the bottom lands precisely.

Infinite scroll (endReached)

The Shape A turnkey path: bind (endReached) on [forVirtualViewport] and it builds the infinite-scroll detector internally, firing once when the rendered window comes within the overscan of the end. The consumer owns the fetch and appends the next page; the detector re-arms when the bound count changes or the window scrolls out of the threshold and back in.

loaded: 30 / 600 โ€” status: idle

Vertical list

<div #scroll role="list" aria-label="Rows" tabindex="0" style="overflow: auto; height: 400px">
  <div [style.height.px]="v.totalSize()" style="position: relative">
    @for (item of v.virtualItems(); track item.key) {
    <div
      role="listitem"
      [attr.data-index]="item.index"
      [attr.aria-setsize]="items().length"
      [attr.aria-posinset]="item.index + 1"
      [style.position]="'absolute'"
      [style.top.px]="item.start"
      [style.height.px]="item.size"
      [style.width]="'100%'"
    >
      {{ items()[item.index] }}
    </div>
    }
  </div>
</div>
readonly items = signal(Array.from({ length: 10000 }, (_, i) => `Row ${i}`));
readonly scrollRef = viewChild<ElementRef<HTMLElement>>('scroll');
readonly scrollElement = computed(() => this.scrollRef()?.nativeElement ?? null);

readonly v = injectVirtualizer({
  count: computed(() => this.items().length),
  estimateSize: () => 40,
  scrollElement: this.scrollElement,
});

The spacer div (the one bound to totalSize()) is position: relative so the absolutely positioned item slices stay inside the scroll container. Each item is positioned with top: item.start instead of translateY so jsdom-based tests can read the value without CSS layout; prefer transform: translateY(item.start + 'px') translateZ(0) in production for GPU compositing.

Dynamic item heights

When items have variable heights, query the rendered elements and feed each one to measureElement so the virtualizer refines its estimates. The item element must carry [attr.data-index]="item.index" so the virtualizer can look up which row the element belongs to:

@for (item of v.virtualItems(); track item.key) {
<div
  #row
  role="listitem"
  [attr.data-index]="item.index"
  [attr.aria-setsize]="items().length"
  [attr.aria-posinset]="item.index + 1"
  [style.position]="'absolute'"
  [style.top.px]="item.start"
  [style.width]="'100%'"
>
  {{ items()[item.index] }}
</div>
}
readonly rows = viewChildren<ElementRef<HTMLElement>>('row');

constructor() {
  afterEveryRender(() => {
    for (const row of this.rows()) {
      this.v.measureElement(row.nativeElement);
    }
  });
}

Horizontal list

Set orientation: 'horizontal' and apply translateX instead of translateY. The totalSize() drives the spacer's width rather than height:

<div
  #scroll
  role="list"
  aria-label="Rows"
  tabindex="0"
  style="overflow: auto; display: flex; width: 600px"
>
  <div [style.width.px]="v.totalSize()" style="position: relative; height: 100%">
    @for (item of v.virtualItems(); track item.key) {
    <div
      role="listitem"
      [attr.data-index]="item.index"
      [attr.aria-setsize]="items().length"
      [attr.aria-posinset]="item.index + 1"
      [style.position]="'absolute'"
      [style.left.px]="item.start"
      [style.width.px]="item.size"
      [style.height]="'100%'"
    >
      {{ items()[item.index] }}
    </div>
    }
  </div>
</div>
readonly v = injectVirtualizer({
  count: computed(() => this.items().length),
  estimateSize: () => 80,
  scrollElement: this.scrollElement,
  orientation: 'horizontal',
});

In a right-to-left layout the first item sits at the right edge of the scroll container, so position each item with [style.right.px]="item.start" instead of left. The core reads the direction in effect at the scroll element (its own dir attribute or its nearest ancestor's, then <html dir>) and follows a change at runtime; pass dir to set it yourself. item.start, scrollToIndex and scrollToOffset stay measured from the inline start in both directions.

Jumping to an item

this.v.scrollToIndex(500, { align: 'start' });

align accepts 'start' | 'center' | 'end' | 'auto' (default). 'auto' scrolls the minimum amount needed to bring the item into view.

With measured rows, the scroll keeps correcting its position for a few frames while the rows around the target are measured. A new scrollToIndex or scrollToOffset replaces the one in progress, and a scroll the user makes stops it. To stop it without starting another, for instance when your own pointer gesture takes over the container, call cancelScroll(): the container stays where it is. [forVirtualReorder] does this when a pointer drag lifts a row.

Drag-reorder

[forVirtualReorder] makes a windowed *forVirtualFor list reorderable by pointer and keyboard, translating the drop into dataset-absolute indices so the right item moves even when the lifted row scrolls out of the rendered window. It composes [forDropList], so it ships from its own entry point rather than this one.

โ†’ forty-cdk/virtual-reorder

Infinite scroll

Two shapes are available: a turnkey output on [forVirtualViewport] (Shape A) and a composable injectInfiniteScroll core for manual wiring (Shape B).

Shape A โ€” (endReached) output

Wire directly onto [forVirtualViewport]; the viewport builds the detector internally:

<div
  forVirtualViewport
  [virtualCount]="rows().length"
  [estimateSize]="44"
  (endReached)="loadMore()"
  role="list"
  aria-label="Rows"
  tabindex="0"
  style="height: 400px"
>
  <div *forVirtualFor="let row of rows(); let item = virtualItem" role="listitem">
    {{ row.label }}
  </div>
</div>

Shape B โ€” injectInfiniteScroll

Compose with the headless core when you need pending state or custom threshold/disabled. The consumer owns the fetch and the data accumulation; the library decides when to ask:

readonly v = injectVirtualizer({ count: this.count, estimateSize: () => 40, scrollElement: this.scrollEl });

readonly loader = injectInfiniteScroll({
  range: this.v.range,
  count: this.count,
  disabled: computed(() => !this.hasMore()),
  onLoadMore: () => this.fetchNextPage(),
});

The detector fires once per threshold crossing, is suppressed while the onLoadMore promise is pending (loader.pending() reflects the in-flight state), and re-arms when count changes (a page was appended) or the window scrolls out of the threshold and back in. A page appended while the promise is still pending fires the next load as soon as it settles, if the window is still near the end. A rejected promise clears pending without re-firing, so the user retries a failed load by scrolling back past the threshold. An empty [0, 0] window (including SSR off-browser) never fires. The consumer owns the fetch, deduplication, and error handling. Angular resource() / httpResource() are a natural fit.

OptionTypeDefaultDescription
range
Signal
requiredThe rendered window from injectVirtualizer(...).range.
count
Signal
requiredReactive total number of currently-loaded items.
threshold
number
5Fire when the window's last index is within this many items of count.
disabled
Signal
โ€”When true the detector never fires.
onLoadMore
() => void | Promise<unknown>
requiredCalled once per threshold crossing; returning a promise arms pending.

Composing into a list primitive

range lets the windowing core plug directly into a list primitive's [visibleRange] input without the consumer re-deriving the window from virtualItems(). The primitive uses [visibleRange] to keep aria-setsize / aria-posinset and aria-activedescendant correct across row recycling: it tracks option data by absolute index so options scrolled out of view are still reachable by keyboard.

The inputs live on each primitive's opt-in virtualized directive, placed on the same element as its root: [forListboxVirtualized], [forSelectVirtualized], [forComboboxVirtualized] or [forTreeVirtualized]. Import it from the primitive's own entry point; a root without it never bundles the virtualized navigation engine.

forCombobox forComboboxVirtualized [totalCount]="filtered().length" [visibleRange]="v.range()"
(scrollToIndex)="v.scrollToIndex($event)"

See the Combobox README for the complete worked example wiring [forCombobox] with injectVirtualizer over a 100k-item list.

API

Options

PropertyTypeDescription
count
Signal
Reactive total number of items.
Default: required
estimateSize
(index: number) => number
Estimated pixel size along the scroll axis for the item at index.
Default: required
scrollElement
Signal
Reactive scroll container.
Default: required
orientation
'vertical' | 'horizontal'
Scroll axis.
Default: 'vertical'
dir
WritingDirection | Signal<WritingDirection>
Writing direction of a horizontal list. In 'rtl' the first item sits at the right edge and offsets grow leftwards. Ignored when vertical.
Default: the direction in effect at scrollElement
overscan
number
Extra items to render beyond the visible window on each side.
Default: 5
getItemKey
(index: number) => string | number
Stable key per item; used by @for (track item.key). Recomputed when count or dataVersion changes.
Default: (i) => i
dataVersion
Signal
The data getItemKey reads, usually the array signal itself. Each new value recomputes every key, so a same-length reorder moves each keyed row and its measured size with its item.
Default: โ€”
estimateVersion
Signal
What estimateSize reads, usually the signal holding the estimate. Each new value after the first render re-estimates every item not yet measured; a measured item keeps its size.
Default: โ€”
scrollMargin
number | Signal<number>
The list's offset in pixels from the start of the scroll container's content: the size of whatever the scroller holds before the list. Every item's start and every scrollToIndex target include it; totalSize does not, and scrollToOffset stays an absolute container offset.
Default: 0

Returned handle

MemberTypeDescription
virtualItems
Signal
Items in the current visible window plus overscan.
totalSize
Signal
Total scroll size in pixels (drives the spacer element).
range
Signal
The [firstIndex, lastIndex + 1) rendered window, [0, 0] when empty. Feeds a list primitive's [visibleRange].
scrollToIndex
method
Scroll the container so the item at index is in view.
scrollToOffset
method
Scroll to an absolute pixel offset.
cancelScroll
method
Stop a scrollToIndex / scrollToOffset still correcting its position, leaving the container where it is.
measureElement
method
Record the measured size of a rendered item element.
measurementFor
method
The item at index with its measured start and size, scrollMargin included, or null before the first browser render or for an index out of range.

ForVirtualViewport

[forVirtualViewport] / <for-virtual-viewport>, exported as forVirtualViewport.

PropertyTypeDescription
virtualCount
number
Total number of items in the full list.
Default: required
estimateSize
number | ((index: number) => number)
Estimated item size in pixels along the scroll axis, as one number or per index.
Default: 50
orientation
'vertical' | 'horizontal'
Scroll axis. Read once when the viewport initializes.
Default: 'vertical'
overscan
number
Extra items rendered beyond the visible window on each side. Read once when the viewport initializes.
Default: 5
dir
WritingDirection | null
Writing direction, reflected to the host dir attribute when set or declared. A horizontal list in RTL starts at the right edge.
Default: the inherited direction
getItemKey
(index: number) => string | number
Stable key per item, recomputed when *forVirtualFor receives a new array.
Default: the index
endReached
output void
Emits when the rendered window nears the end of the list, as described under Infinite scroll.
virtualItems
Signal
Items in the current visible window plus overscan, plus a row pinned by setReorderingIndex.
totalSize
Signal
Total scroll size in pixels.
range
Signal
The [firstIndex, lastIndex + 1) rendered window, [0, 0] when empty.
scrollToIndex
method
Scroll so the item at index is in view. No-op until initialized.
scrollToOffset
method
Scroll to an absolute pixel offset. No-op until initialized.
cancelScroll
method
Stop a scrollToIndex / scrollToOffset still correcting its position.
measureElement
method
Record the measured size of a rendered item element.
setReorderingIndex
method
Keep the row at index rendered while it is scrolled out of the window, or null to release it. Used by [forVirtualReorder].

ForVirtualFor

PropertyTypeDescription
forVirtualForOf
readonly T[]
The full list of items; the rows rendered are the viewport's virtualItems().
Default: required

Each row's template context exposes $implicit (the row data), virtualItem (its VirtualItem), index (its index in the full list) and count (the full list length).

Accessibility

Virtual lists render only a window of items, so screen readers see a shorter list than the true total. Bind the full list size so assistive technology announces the real count:

  • aria-setsize: the total number of items in the full (non-windowed) list.
  • aria-posinset: the 1-based position of the item in that full list (item.index + 1).

The pair is announced only on a role that supports it: listitem, option, row, treeitem, article, and a few more. They are not global attributes, so on a role-less <div> the browser drops them and screen readers announce no list and no count. Give each row a supporting role and its container the matching one, with a label:

<div role="list" aria-label="Rows" tabindex="0">
  <div role="listitem" [attr.aria-setsize]="items().length" [attr.aria-posinset]="item.index + 1">
    {{ items()[item.index] }}
  </div>
</div>

*forVirtualFor writes the pair for you, but the role is still yours to set on the row root.

The scroll container needs a Tab stop when the rows hold nothing focusable. Safari does not make a scroll container focusable on its own, so without tabindex="0" a keyboard user there cannot scroll the list at all. Pair the Tab stop with a :focus-visible style.

The directive never takes a focused row's node out of the document. A row that holds focus stays mounted when a scroll or a reorder takes it out of the rendered window, and is recycled once focus moves out of it. A keyed row ([getItemKey] on [forVirtualViewport]) is kept with its item, so it follows the item a reorder moves; an index-keyed row is kept at its index.

Wrapping in a design system

ForVirtualViewport is a component: its own template renders the sizer the rows are positioned in. A subclass inherits no template, so do not subclass it. A @Directive subclass throws NG0903, and a @Component subclass renders no sizer, so its list cannot scroll. Compose the viewport in your wrapper's template instead, and stamp the consumer's row template into each row with NgTemplateOutlet:

import { NgTemplateOutlet } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  TemplateRef,
  contentChild,
  input,
} from '@angular/core';
import { ForVirtualFor, ForVirtualViewport } from 'forty-cdk/virtualization';

@Component({
  selector: 'my-virtual-list',
  imports: [ForVirtualViewport, ForVirtualFor, NgTemplateOutlet],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div
      forVirtualViewport
      class="my-virtual-list"
      [virtualCount]="items().length"
      [estimateSize]="estimateSize()"
      role="list"
      [attr.aria-label]="ariaLabel()"
      tabindex="0"
    >
      <div
        *forVirtualFor="let item of items(); let index = index"
        class="my-virtual-list-row"
        role="listitem"
      >
        <ng-container *ngTemplateOutlet="row(); context: { $implicit: item, index: index }" />
      </div>
    </div>
  `,
})
export class MyVirtualList<T> {
  readonly items = input.required<readonly T[]>();
  readonly estimateSize = input(44);
  readonly ariaLabel = input<string | null>(null);
  readonly row = contentChild.required(TemplateRef);
}
<my-virtual-list [items]="users()" [estimateSize]="48" ariaLabel="Users">
  <ng-template let-user>{{ user.name }}</ng-template>
</my-virtual-list>

The wrapper re-provides nothing: the viewport in its template provides FOR_VIRTUAL_VIEWPORT_CONTEXT to the rows it renders. When your consumers need scrollToIndex(), expose the viewport with viewChild.required(ForVirtualViewport). The other non-form roots wrap by subclassing; Wrapping non-form roots covers them.