skip to content

With the Angular CDK's virtual scroll viewport, how do you build a jump-to-entry box with scrollToIndex and a 'line N of M' readout with scrolledIndexChange?

level: middleimportance: should knowfreq 32%

answer

  1. a signal query for the viewport
  2. data index, zero-based
  3. index times itemSize, at the top
  4. first visible index, only on change
  5. re-measure when the box resizes

basics

~20 s

Query the CdkVirtualScrollViewport, convert the typed entry number to a zero-based data index and call scrollToIndex(index); bind (scrolledIndexChange) to a signal that holds the first visible index and show it plus one, of the list length.

solid answer

~40 s

Get the viewport with `viewChild.required(CdkVirtualScrollViewport)`. For the jump box, turn the user's 1-based entry number into a clamped, zero-based index into the data array and call `scrollToIndex(index)`; behaviour defaults to `'auto'`, and with the fixed-size strategy it scrolls to index × `itemSize`, so the line lands at the top (near the end the browser clamps it lower). For the readout, bind `(scrolledIndexChange)` to a signal: it emits the data index of the first visible item, only when it changes, not the buffered range. Don't query the DOM for the target right after the call — it renders on the next frame — so keep a highlighted entry id in state. If the panel resizes without a window resize, call `checkViewportSize()`.

code

ts · 31 lines
ts
import {Component, input, signal, viewChild} from '@angular/core';
import {CdkVirtualScrollViewport, ScrollingModule} from '@angular/cdk/scrolling';

@Component({
  selector: 'app-audit-jump',
  imports: [ScrollingModule],
  template: `
    <form (submit)="$event.preventDefault(); jump(entry.valueAsNumber)">
      <input #entry type="number" min="1" aria-label="Entry number" />
      <button type="submit">Go</button>
    </form>
    <p>Line {{ firstVisible() + 1 }} of {{ lines().length }}</p>
    <cdk-virtual-scroll-viewport itemSize="32" class="log" (scrolledIndexChange)="firstVisible.set($event)">
      <div class="line" *cdkVirtualFor="let line of lines()" [class.target]="line.id === targetId()">{{ line.text }}</div>
    </cdk-virtual-scroll-viewport>
  `,
  styles: `.log { height: 480px; } .line { height: 32px; box-sizing: border-box; }`,
})
export class AuditJump {
  readonly lines = input.required<{id: number; text: string}[]>();
  readonly firstVisible = signal(0);
  readonly targetId = signal<number | null>(null);
  private readonly viewport = viewChild.required(CdkVirtualScrollViewport);

  jump(entryNumber: number) {
    if (!Number.isFinite(entryNumber) || this.lines().length === 0) return;
    const index = Math.min(Math.max(Math.trunc(entryNumber) - 1, 0), this.lines().length - 1);
    this.targetId.set(this.lines()[index].id);
    this.viewport().scrollToIndex(index);
  }
}

go deeper

for a junior

Remember the pair: scrollToIndex moves to a data index, and the scrolledIndexChange output reports the first visible data index when it changes.

for a middle

Explain the details that make a jump box correct: one-based input versus zero-based index, clamping, landing at the top, and why the row is not in the DOM straight after the call.

for a senior

Cover what breaks in production: layout resizes that need checkViewportSize, filters that change what an index means, and strategies such as autosize that do not support these APIs.

for a principal

Decide how the viewer replaces find-in-page — client-side search, a server query or deep links to entry ids — and keep the virtual list as a rendering detail behind that navigation model.

## The two APIs A security audit log of 100,000 fixed-height lines cannot be searched with the browser's find-in-page, because almost none of its lines are in the DOM. The CDK viewport offers two index-based APIs that make in-app navigation possible: - **`scrollToIndex(index, behavior = 'auto')`** — a method on `CdkVirtualScrollViewport`. It delegates to the active scroll strategy; the fixed-size strategy turns it into `scrollToOffset(index × itemSize, behavior)`. - **`scrolledIndexChange`** — an output that emits the **index of the first visible item** whenever that index changes. Both speak in **data indexes**: positions in the array (or DataSource output) given to `*cdkVirtualFor`, starting at 0, never positions within the rendered slice. ## Building the jump box 1. **Get the viewport.** In a standalone component, `viewChild.required(CdkVirtualScrollViewport)` returns a signal holding the instance once the view exists. 2. **Translate the entry number.** Users type 1-based line numbers; the API wants zero-based indexes, so subtract one. If the viewer shows a filtered subset of the log, the typed number is an entry identifier rather than a position — keep a map from entry id to its current index, rebuilt whenever the filtered array changes. 3. **Validate and clamp.** Ignore empty or non-numeric input, and clamp into 0 … length − 1 so a typo past the end lands on the last line rather than nowhere. 4. **Scroll.** Call `scrollToIndex(index)`. The default `'auto'` behaviour jumps instantly; `'smooth'` animates through every intermediate position, making the viewport render ranges along the way, which is rarely worth it across tens of thousands of lines. 5. **Mark the target in state, not in the DOM.** The target row is not rendered synchronously: the scroll raises a scroll event, the viewport recomputes the range on the next animation frame and then runs change detection. Store the target entry id in a signal and bind a highlight class on the row whose id matches, so the highlight appears whenever that row renders. **Where the line lands:** the fixed-size strategy scrolls to index × `itemSize`, which puts the line at the **top** of the viewport. For the last screenful of the log the browser cannot scroll that far, so the line appears lower down — expected, not a bug. ## The "line N of M" readout Bind `(scrolledIndexChange)="firstVisible.set($event)"` and render `firstVisible() + 1` of `lines().length`. Details that matter: - **It emits on change only.** The fixed-size strategy computes the floor of scroll offset ÷ `itemSize` and filters out repeats, so scrolling within one line emits nothing. - **It is lazy.** The viewport subscribes to the strategy's index stream only when something listens to the output, because for some strategies the calculation costs something. It delivers each value after a microtask, inside Angular's zone. - **It ignores the buffer.** It reports the first *visible* line. For the range actually rendered, including buffer rows, read `getRenderedRange()` or subscribe to `renderedRangeStream`. | API | What it gives you | Typical use | |---|---|---| | `scrollToIndex(i, behavior?)` | scrolls so item `i` is at the start | jump box, "go to newest" | | `scrollToOffset(px, behavior?)` | scrolls to a pixel offset | restoring a saved position | | `scrolledIndexChange` | first visible data index, on change | "line N of M", syncing a minimap | | `measureScrollOffset()` | current offset in px | saving a position | | `getRenderedRange()` / `renderedRangeStream` | rendered start and end, buffer included | prefetching data near the range | | `checkViewportSize()` | re-measures the viewport and re-renders | after a layout-only resize | ## Edge cases that bite in a real viewer - **Resizes without a window resize.** The viewport measures its own height at start-up and again when the window resizes or the device rotates. A side panel that grows from 300px to 600px is invisible to it, so it keeps rendering for 300px and the lower half stays blank; call `checkViewportSize()` after such layout changes. - **Data replaced under the readout.** Applying a filter keeps `firstVisible` as a position, which may now point at a different entry; reset it or re-jump to the entry the user was reading. - **Strategy support.** `scrollToIndex` and `scrolledIndexChange` belong to the `VirtualScrollStrategy` contract. The fixed-size strategy implements both; the experimental autosize strategy throws in development mode when you call the method or listen to the output, so a jump box needs fixed rows or a custom strategy. - **Out-of-range indexes.** Passing an index beyond the data simply scrolls as far as the browser allows; clamping in your own code keeps the highlight and the scroll position consistent.

  • Why not let users press Ctrl+F to find an audit entry?
    Browser find-in-page searches the DOM, and the viewport renders a few dozen of the 100,000 lines, so a match further down cannot be found or scrolled to. Search the data array instead — in memory or on the server — and call `scrollToIndex` with the hit's index, highlighting it through component state.
  • After scrollToIndex, how do you move keyboard focus to the target line?
    Wait for the render: the scroll is processed on the next animation frame and change detection then creates the row, so the element does not exist when `scrollToIndex` returns. Keep the target id in a signal and let the row act when it renders — for example a small directive on the row that calls `focus()` on its host when its id matches — instead of querying the DOM straight after the call.

  • scrollToIndex takes the index within the rendered rows, not in the data.
  • scrolledIndexChange emits the scroll offset in pixels on every scroll event.
  • After scrollToIndex returns, the target row is already in the DOM and can be queried.
  • scrollToIndex centres the requested line in the viewport.
  • The viewport notices any change to its own height automatically.
  • scrolledIndexChange includes the buffer rows rendered above the visible area.