skip to content

In an Angular CDK virtual scroll of a message thread whose rows differ in height, what are your options, and what does each cost?

level: seniorimportance: should knowfreq 27%

answer

  1. the strategy is pluggable
  2. make rows uniform first
  3. experimental package, missing methods
  4. your own offsets table
  5. provide it through an injection token

basics

~20 s

Make rows uniform so the fixed-size strategy works; use the experimental autosize directive, which estimates heights but lacks scrollToIndex and scrolledIndexChange; or write a custom VirtualScrollStrategy provided through VIRTUAL_SCROLL_STRATEGY that computes offsets from heights you know.

solid answer

~40 s

The fixed-size strategy assumes one `itemSize`, so uneven messages make content jump and index jumps miss. Options: first, **make rows uniform** — clamp each message to a fixed height and open the full text elsewhere; cheapest and keeps every API. Second, the **`autosize` directive from `@angular/cdk-experimental/scrolling`**: it measures rendered rows and estimates unseen ones from an average, but it is experimental, its scrollbar is an estimate, and calling `scrollToIndex` or listening to `scrolledIndexChange` throws in development mode — painful for 'jump to newest'. Third, a **custom `VirtualScrollStrategy`** provided as `VIRTUAL_SCROLL_STRATEGY` on the component: if each message's height follows from its data, keep an offsets table and binary-search it; you own the math and must keep heights true. `appendOnly` alone is not a fix: it keeps rendered rows and grows the DOM.

code

ts · 39 lines
ts
import {Injectable} from '@angular/core';
import {CdkVirtualScrollViewport, VirtualScrollStrategy} from '@angular/cdk/scrolling';
import {Subject, distinctUntilChanged} from 'rxjs';

@Injectable()
export class KnownHeightStrategy implements VirtualScrollStrategy {
  private readonly firstIndex = new Subject<number>();
  readonly scrolledIndexChange = this.firstIndex.pipe(distinctUntilChanged());
  private viewport: CdkVirtualScrollViewport | null = null;
  private tops = [0]; // tops[i] = top of message i; last entry = total height

  setHeights(heights: number[]) {
    this.tops = [0];
    for (const h of heights) this.tops.push(this.tops[this.tops.length - 1] + h);
    this.onDataLengthChanged();
  }
  attach(viewport: CdkVirtualScrollViewport) { this.viewport = viewport; this.onDataLengthChanged(); }
  detach() { this.firstIndex.complete(); this.viewport = null; }
  onContentScrolled() { this.update(); }
  onDataLengthChanged() { this.viewport?.setTotalContentSize(this.tops[this.tops.length - 1]); this.update(); }
  onContentRendered() {}
  onRenderedOffsetChanged() {}
  scrollToIndex(index: number, behavior: ScrollBehavior) { this.viewport?.scrollToOffset(this.tops[index] ?? 0, behavior); }

  private indexAt(px: number) {
    let lo = 0, hi = this.tops.length - 2;
    while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (this.tops[mid] <= px) lo = mid; else hi = mid - 1; }
    return Math.max(lo, 0);
  }
  private update() {
    if (!this.viewport) return;
    const top = this.viewport.measureScrollOffset(), size = this.viewport.getViewportSize();
    const start = this.indexAt(top - 300);
    const end = Math.min(this.viewport.getDataLength(), this.indexAt(top + size + 300) + 1);
    this.viewport.setRenderedRange({start, end});
    this.viewport.setRenderedContentOffset(this.tops[start]);
    this.firstIndex.next(this.indexAt(top));
  }
}

go deeper

for a junior

Know that the fixed-size strategy needs equal rows and that the CDK has other strategies, one experimental, for uneven ones.

for a middle

Explain what VIRTUAL_SCROLL_STRATEGY is for and list what the autosize directive gives and lacks, starting with scrollToIndex and scrolledIndexChange.

for a senior

Choose for the thread and defend it: uniform rows when the product allows, a custom offsets strategy when heights follow from data, and autosize only with its missing APIs and experimental status accepted.

for a principal

Weigh owning a scroll strategy in your codebase against an experimental dependency or a product compromise, and decide who maintains the height contract as message layouts evolve.

## Why the fixed-size strategy fails here In the Angular CDK, `<cdk-virtual-scroll-viewport itemSize="…">` uses a **fixed-size strategy** that computes every position as index × `itemSize` and never measures a row. A message thread breaks that assumption: a one-line reply, a five-line paragraph and a message with an attachment card differ in height. With a single `itemSize`, the rendered block is placed at the wrong offset whenever the range shifts (content **jumps**), the scrollbar length is wrong, and `scrollToIndex` misses. The viewport itself does not care how heights are computed — it delegates everything to whatever **`VirtualScrollStrategy`** is injected through the **`VIRTUAL_SCROLL_STRATEGY`** token — so the options are about choosing or writing that strategy, or changing the content. ## Option 1 — make the rows uniform Clamp every message to one height: show the first line or two with an ellipsis and open the full message in a side panel. The fixed-size strategy then works unchanged. - **Gains:** fastest strategy, exact scrollbar, `scrollToIndex` and `scrolledIndexChange` work. - **Costs:** a product compromise — readers cannot read long messages inline. ## Option 2 — the experimental autosize strategy `@angular/cdk-experimental/scrolling` provides a directive on `cdk-virtual-scroll-viewport[autosize]`, backed by `AutoSizeVirtualScrollStrategy`. It takes `minBufferPx` and `maxBufferPx` (100 and 200 by default), measures the rows it has rendered and estimates unseen ones from a running **average item size** (50px until it has samples). - **Gains:** no height bookkeeping; rows can be any height. - **Costs:** 1. It is **experimental** — its own guide warns it may have bugs and change at any time, and the CDK's main guide says it is not ready for production use. 2. `scrollToIndex` and `scrolledIndexChange` are **not implemented**: in development mode, calling the method or subscribing to the output throws an error saying it is not supported for the autosize strategy, and in a production build the method does nothing and the output never emits. "Jump to newest message" and "message N of M" need another route. 3. The total size is an estimate, so the scrollbar thumb can resize and drift as more rows are measured. 4. Measuring costs layout work, so it is slower than the fixed-size strategy. ## Option 3 — a custom `VirtualScrollStrategy` Implement the interface and provide it on the component that contains the viewport: ```ts providers: [ KnownHeightStrategy, {provide: VIRTUAL_SCROLL_STRATEGY, useExisting: KnownHeightStrategy}, ], ``` The interface has `scrolledIndexChange`, `attach`, `detach`, `onContentScrolled`, `onDataLengthChanged`, `onContentRendered`, `onRenderedOffsetChanged` and `scrollToIndex`. The strategy drives the viewport through its public methods: `setTotalContentSize`, `setRenderedRange`, `setRenderedContentOffset`, `measureScrollOffset`, `getViewportSize`, `getDataLength` and `scrollToOffset`. When a message's height **follows from its data** — a known height per layout type, for instance — keep a cumulative offsets table and binary-search it for the first visible index. That gives an exact scrollbar and a working `scrollToIndex`. - **Gains:** exact positions, every API works, no experimental dependency. - **Costs:** you own the math and its tests, and the heights must stay true. If real rendered heights drift from your table (fonts, viewport width changing line wraps), you are back to jumps; measuring rendered rows in `onContentRendered` with the viewport's `measureRangeSize` fixes that, but at that point you are rebuilding autosize. ## What `appendOnly` does and does not solve `appendOnly` on the viewport keeps every row rendered so far in the DOM and pins the rendered block to the top, so rows already seen keep their natural layout. It still needs a strategy underneath, the spacer is still computed by that strategy, and the DOM grows with how far the user has scrolled — on a long thread that gradually erodes the reason for virtualizing. ## Side by side | Option | Scrollbar | `scrollToIndex` / `scrolledIndexChange` | Stability | Main cost | |---|---|---|---|---| | Uniform rows + `itemSize` | exact | yes | stable API | design compromise | | `autosize` (experimental) | estimated, drifts | throw in dev mode when used | experimental | missing APIs, measuring | | Custom strategy | exact if heights are true | yes, you implement them | your code | math and upkeep | | `appendOnly` on top of a strategy | from the strategy | from the strategy | stable API | DOM grows with scrolling | Heights that change after render — an image loading above the reading position — are a separate problem of keeping the reader's place, and no CDK strategy solves it for you.

  • With the autosize strategy, how would you still offer 'jump to newest message'?
    Not through `scrollToIndex`, which autosize does not implement. The viewport's own `scrollToOffset` bypasses the strategy, so scrolling to a very large offset lands at the end of the thread because the browser clamps it; the estimated total size means it can take a render pass or two to settle. If precise jumps matter, that is the argument for a custom strategy.
  • Why provide the custom strategy with useExisting rather than useClass?
    The component also needs the same instance, to call `setHeights` when messages arrive. Listing the class as a provider and aliasing `VIRTUAL_SCROLL_STRATEGY` to it with `useExisting` gives the viewport and the component one shared object. Listing the class and also putting `useClass` on the token creates two instances, and the component would feed the one the viewport never reads.

  • The autosize strategy is a stable input of the CDK viewport in @angular/cdk/scrolling.
  • Autosize supports scrollToIndex by estimating from the average row height.
  • appendOnly makes uneven row heights work without any other change.
  • A custom strategy is passed to the viewport through its itemSize input.
  • Setting itemSize to the average message height is close enough for a thread.
  • A custom scroll strategy is registered globally with ScrollDispatcher.

Assumes Angular CDK 22, where the autosize strategy still lives in @angular/cdk-experimental and does not implement scrollToIndex or scrolledIndexChange.