← Back to Angular, page 4

angular-0078 · Medium mid

Build a long list with the CDK virtual scroll that loads more items when the user nears the end. How does virtual scrolling work and what are its limits?

Virtual scrolling renders only the rows that are visible plus a small buffer, and positions them inside a container whose scroll height matches the full list. With cdk-virtual-scroll-viewport and *cdkVirtualFor, you set a fixed item size, a fixed viewport height, and load the next page when the rendered range reaches the end.

Full answer

Rendering 50,000 rows creates 50,000 DOM nodes, which makes scrolling and updates slow and uses a lot of memory. Virtual scrolling renders only what the user can see.

How it works: the viewport has a fixed height and a spacer that is as tall as the whole list would be (itemSize times the item count). On scroll, the CDK calculates which indexes are visible, renders those plus a buffer, and moves them to the right offset with a transform. The browser sees a few dozen nodes, but the scroll bar looks like a full list.

Set-up:

  • Import ScrollingModule (or the standalone directives).
  • <cdk-virtual-scroll-viewport itemSize="48" class="viewport"> with a CSS height. Without a height nothing renders.
  • *cdkVirtualFor="let row of rows(); trackBy: trackById" instead of @for.
  • FixedSizeVirtualScroll is the default strategy, so every row must have the same height. For variable heights the CDK offers an experimental autosize strategy, or use the Material or ngx-virtual-scroller alternatives.

Infinite loading: listen to (scrolledIndexChange), or read viewport.getRenderedRange().end. When end is near rows().length (for example within 10 rows) and no request is in flight, request the next page and append it with a new array ([...old, ...next]). Guard with a loading flag and an allLoaded flag, and handle errors with a retry button.

Limits and trade-offs:

  • Browser find (Ctrl+F) cannot find text in rows that are not rendered.
  • Screen readers see only rendered rows, so provide aria-rowcount, aria-setsize, or a text summary for accessibility.
  • Variable row heights, expanding rows, and sticky headers need extra work.
  • For lists under a few hundred rows, plain @for is simpler and enough.
  • Pagination can be better than infinite scroll when users need to find a position or reach the footer.
typescript
import { CdkVirtualScrollViewport, ScrollingModule } from '@angular/cdk/scrolling';
import { Component, signal, viewChild } from '@angular/core';

interface Row {
  id: number;
  label: string;
}

const PAGE_SIZE = 50;
const TOTAL = 200;

@Component({
  selector: 'app-long-list',
  imports: [ScrollingModule],
  template: `
    <p aria-live="polite">{{ rows().length }} of {{ total }} loaded</p>

    <cdk-virtual-scroll-viewport itemSize="40" class="viewport" (scrolledIndexChange)="checkEnd()">
      <div *cdkVirtualFor="let row of rows(); trackBy: trackById" class="row">{{ row.label }}</div>
    </cdk-virtual-scroll-viewport>

    @if (loading()) {
      <p>Loading more...</p>
    }
  `,
  styles: `
    .viewport { height: 320px; border: 1px solid #aaa; }
    .row { height: 40px; line-height: 40px; padding: 0 8px; }
  `,
})
export class LongListComponent {
  protected readonly total = TOTAL;
  readonly rows = signal<Row[]>([]);
  readonly loading = signal(false);
  private readonly viewport = viewChild.required(CdkVirtualScrollViewport);

  constructor() {
    this.loadMore();
  }

  trackById(_index: number, row: Row): number {
    return row.id;
  }

  checkEnd(): void {
    const end = this.viewport().getRenderedRange().end;
    if (end >= this.rows().length - 10) {
      this.loadMore();
    }
  }

  private loadMore(): void {
    if (this.loading() || this.rows().length >= TOTAL) {
      return;
    }
    this.loading.set(true);
    setTimeout(() => {
      const start = this.rows().length;
      const next = Array.from({ length: PAGE_SIZE }, (_, i) => ({ id: start + i + 1, label: `Row ${start + i + 1}` }));
      this.rows.update((old) => [...old, ...next]);
      this.loading.set(false);
    }, 300);
  }
}

Angular 20.3 with CDK 20.2, strict template check passes. The fake loader waits 300 ms and returns 50 more rows, up to 200.

Key points

  • Render only the visible rows and use a spacer for the full height.
  • Needs a fixed viewport height and a fixed item size with the default strategy.
  • Load more when the rendered range nears the end, with `loading` and `allLoaded` guards.
  • Costs: browser find, accessibility, and variable heights are harder.

Common mistakes

  • Forgetting to give the viewport a height, so nothing renders.
  • Requesting the next page repeatedly while one request is in flight.
  • Mutating the array with `push`, so the viewport does not update.

Follow-ups

  • How would you support rows of different heights?
  • How would you keep screen reader users informed about the list size?
  • When would you choose pagination over infinite scroll?

Tips

  • Describe the technique (spacer plus rendered window) in one sentence.
  • State the limits. A solution without trade-offs sounds untested.
  • Mention guards for repeated loads.

Evaluation rubric

  • Understands how the virtualisation works.
  • Implements loading with guards correctly.
  • Mentions accessibility and when not to use it.