11. CDK Virtual Scrolling
Rendering 100,000 items without breaking a sweat
Rendering a list of 50 items is trivial. Rendering 10,000 is a problem. The browser has to create 10,000 DOM elements, lay them all out, and keep them in memory — even though the user can only see ~20 at a time. The CDK's Virtual Scroll solves this by rendering only the items currently in the viewport, recycling DOM elements as the user scrolls.
The Problem: DOM Is Expensive
Every DOM element costs memory and layout time. A simple *ngFor over 10,000 items creates 10,000 real DOM nodes:
// This creates 10,000 DOM elements
@Component({
template: `
<div class="list" style="height:400px;overflow:auto;">
<div *ngFor="let item of items" class="row">
{{ item.name }} — {{ item.value }}
</div>
</div>
`
})
export class NaiveListComponent {
items = Array.from({ length: 10000 }, (_, i) => ({
name: `Item ${i}`,
value: Math.random().toFixed(4)
}));
}
The initial render is slow. Scrolling is janky. Memory usage balloons. Each row may also have bindings, event listeners, and child components — multiplied by 10,000.
The Solution: Virtual Scrolling
Virtual scrolling renders only the visible items plus a small buffer. As the user scrolls, items leaving the viewport are destroyed and new items entering the viewport are created. The total number of DOM elements stays roughly constant regardless of list size.
import { ScrollingModule } from '@angular/cdk/scrolling';
@Component({
imports: [ScrollingModule],
template: `
<cdk-virtual-scroll-viewport itemSize="48" class="viewport">
<div *cdkVirtualFor="let item of items" class="row">
{{ item.name }} — {{ item.value }}
</div>
</cdk-virtual-scroll-viewport>
`,
styles: [`
.viewport { height: 400px; }
.row { height: 48px; display: flex; align-items: center; padding: 0 16px; }
`]
})
export class VirtualListComponent {
items = Array.from({ length: 100000 }, (_, i) => ({
name: `Item ${i}`,
value: Math.random().toFixed(4)
}));
}
That's 100,000 items rendered with ~20 DOM nodes. The viewport maintains a scrollbar that reflects the total content height, but only materializes the rows you can see.
How It Works Internally
The virtual scroll viewport manages three things:
1. Total content size
The viewport calculates the total scrollable height based on the number of items and their size:
totalHeight = itemCount * itemSize
// 100,000 * 48px = 4,800,000px
It creates a spacer element with this height so the browser's native scrollbar works correctly.
2. Visible range
As the user scrolls, the viewport calculates which items are currently visible:
firstVisible = Math.floor(scrollTop / itemSize)
lastVisible = firstVisible + Math.ceil(viewportHeight / itemSize)
// With buffer:
renderStart = Math.max(0, firstVisible - bufferSize)
renderEnd = Math.min(itemCount, lastVisible + bufferSize)
3. DOM recycling
Only items in [renderStart, renderEnd] have DOM nodes. When the user scrolls:
- Items scrolling out of range are destroyed
- Items scrolling in to range are created
- The rendered items are positioned using a CSS
transform: translateY()to appear at the correct scroll position
Fixed vs. Auto-Size Items
Fixed size (default)
When all items have the same height, use itemSize:
<cdk-virtual-scroll-viewport itemSize="48">
<div *cdkVirtualFor="let item of items" class="row">
{{ item.name }}
</div>
</cdk-virtual-scroll-viewport>
This is the most performant option — the viewport can calculate positions with simple multiplication.
Auto-size (experimental)
When items have variable heights, use autosize:
<cdk-virtual-scroll-viewport autosize>
<div *cdkVirtualFor="let item of items" class="row">
<h3>{{ item.title }}</h3>
<p>{{ item.description }}</p> <!-- variable height -->
</div>
</cdk-virtual-scroll-viewport>
Auto-size measures each item after rendering and caches the heights. Initial scroll estimates may jump slightly as items are measured, but it converges quickly.
*cdkVirtualFor — The Virtual *ngFor
*cdkVirtualFor is a drop-in replacement for *ngFor with the same template syntax:
<div *cdkVirtualFor="let item of items; let i = index; trackBy: trackById"
class="row"
[class.even]="i % 2 === 0">
{{ i }}. {{ item.name }}
</div>
It supports:
let i = indexlet first = first,let last = lastlet even = even,let odd = oddtrackBy(strongly recommended for performance)
Using with Observables
*cdkVirtualFor accepts Observables directly:
@Component({
template: `
<cdk-virtual-scroll-viewport itemSize="48" class="viewport">
<div *cdkVirtualFor="let item of items$" class="row">
{{ item.name }}
</div>
</cdk-virtual-scroll-viewport>
`
})
export class StreamingListComponent {
items$ = inject(DataService).getAllItems(); // Observable<Item[]>
}
No async pipe needed — *cdkVirtualFor subscribes and unsubscribes automatically.
Scrolling Strategies
Buffer size
Control how many extra items are rendered outside the viewport:
<cdk-virtual-scroll-viewport
itemSize="48"
[minBufferPx]="200"
[maxBufferPx]="400">
<!-- ... -->
</cdk-virtual-scroll-viewport>
minBufferPx: minimum pixels of content to render beyond the viewport (triggers rendering)maxBufferPx: maximum pixels of content to render beyond the viewport (how much to add)
Larger buffers give smoother scrolling but use more DOM elements. The defaults work well for most cases.
Horizontal scrolling
<cdk-virtual-scroll-viewport itemSize="200" orientation="horizontal" class="horizontal-viewport">
<div *cdkVirtualFor="let card of cards" class="card">
<img [src]="card.image" [alt]="card.title">
<h3>{{ card.title }}</h3>
</div>
</cdk-virtual-scroll-viewport>
.horizontal-viewport {
height: 300px;
width: 100%;
}
.card {
width: 200px;
display: inline-block;
}
Programmatic Scrolling
The viewport exposes methods for programmatic scroll control:
@Component({
template: `
<div class="controls">
<button (click)="scrollToTop()">Top</button>
<button (click)="scrollToBottom()">Bottom</button>
<button (click)="scrollToIndex(500)">Go to #500</button>
</div>
<cdk-virtual-scroll-viewport itemSize="48" class="viewport">
<div *cdkVirtualFor="let item of items" class="row">{{ item.name }}</div>
</cdk-virtual-scroll-viewport>
`
})
export class ScrollableListComponent {
@ViewChild(CdkVirtualScrollViewport) viewport!: CdkVirtualScrollViewport;
items = Array.from({ length: 10000 }, (_, i) => ({ name: `Item ${i}` }));
scrollToTop() {
this.viewport.scrollToIndex(0, 'smooth');
}
scrollToBottom() {
this.viewport.scrollToIndex(this.items.length - 1, 'smooth');
}
scrollToIndex(index: number) {
this.viewport.scrollToIndex(index, 'smooth');
}
}
Scroll events
React to scroll position changes:
ngAfterViewInit() {
this.viewport.scrolledIndexChange.subscribe(index => {
console.log('First visible index:', index);
// Infinite scroll: load more when near the end
if (index > this.items.length - 50) {
this.loadMore();
}
});
}
Infinite Scroll Pattern
Combine virtual scrolling with on-demand data loading:
@Component({
template: `
<cdk-virtual-scroll-viewport itemSize="64" class="viewport"
(scrolledIndexChange)="onScroll($event)">
<div *cdkVirtualFor="let item of items" class="row">
<h4>{{ item.title }}</h4>
<p>{{ item.subtitle }}</p>
</div>
<div *ngIf="loading" class="loader">Loading more...</div>
</cdk-virtual-scroll-viewport>
`
})
export class InfiniteScrollComponent {
items: Item[] = [];
loading = false;
private page = 0;
private hasMore = true;
constructor(private dataService: DataService) {
this.loadPage();
}
onScroll(firstVisibleIndex: number) {
if (!this.loading && this.hasMore && firstVisibleIndex > this.items.length - 20) {
this.loadPage();
}
}
private loadPage() {
this.loading = true;
this.dataService.getPage(this.page, 50).subscribe(result => {
this.items = [...this.items, ...result.items];
this.hasMore = result.hasMore;
this.page++;
this.loading = false;
});
}
}
Performance Comparison
To give you a sense of the difference, here's what happens when you render large lists with and without virtual scrolling:
| Items | Regular *ngFor |
Virtual Scroll |
|---|---|---|
| 100 | ~5ms, 100 nodes | ~5ms, ~15 nodes |
| 1,000 | ~50ms, 1K nodes | ~5ms, ~15 nodes |
| 10,000 | ~500ms, 10K nodes | ~5ms, ~15 nodes |
| 100,000 | ~5s+, 100K nodes | ~5ms, ~15 nodes |
The virtual scroll time and node count stay nearly constant regardless of list size. The regular *ngFor scales linearly.
When to use virtual scrolling
Use virtual scrolling when your list has more than ~100 items, or when
each item's template is complex (nested components, images, bindings). For short lists
(<50 items), regular *ngFor is simpler and sufficient.
Custom Virtual Scroll Strategy
For advanced cases, implement a custom VirtualScrollStrategy:
import { VirtualScrollStrategy, CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { Observable, Subject } from 'rxjs';
export class GroupedScrollStrategy implements VirtualScrollStrategy {
scrolledIndexChange = new Subject<number>();
private viewport: CdkVirtualScrollViewport | null = null;
private groups: { start: number; height: number }[] = [];
attach(viewport: CdkVirtualScrollViewport) {
this.viewport = viewport;
this.updateTotalContentSize();
}
detach() {
this.viewport = null;
}
onContentScrolled() {
if (!this.viewport) return;
const scrollTop = this.viewport.measureScrollOffset();
const range = this.calculateRange(scrollTop);
this.viewport.setRenderedRange(range);
this.viewport.setRenderedContentOffset(this.getOffset(range.start));
this.scrolledIndexChange.next(range.start);
}
onDataLengthChanged() { this.updateTotalContentSize(); }
onContentRendered() {}
onRenderedOffsetChanged() {}
private calculateRange(scrollTop: number): { start: number; end: number } {
// Custom logic for variable-height groups
// ...
}
}
Register it with a provider:
@Component({
providers: [{
provide: VIRTUAL_SCROLL_STRATEGY,
useFactory: () => new GroupedScrollStrategy()
}],
template: `
<cdk-virtual-scroll-viewport class="viewport">
<div *cdkVirtualFor="let item of items">{{ item.name }}</div>
</cdk-virtual-scroll-viewport>
`
})
export class GroupedListComponent { /* ... */ }
Try It Yourself -- Virtual Scroll Visualizer
Scroll through a list of 100,000 items and watch the DOM recycling in real time. The left panel shows the viewport; the right panel shows which DOM nodes exist, are created, or are destroyed on each scroll frame.
Tips and Gotchas
Always use trackBy
Without trackBy, any data change causes all rendered items to be destroyed and recreated:
<!-- Always include trackBy -->
<div *cdkVirtualFor="let item of items; trackBy: trackById">
Set explicit dimensions
The viewport must have a fixed height (or width for horizontal). Without it, the viewport collapses to zero:
cdk-virtual-scroll-viewport {
height: 400px; // Required!
}
Avoid complex templates per row
Even with virtual scrolling, each rendered row pays the full cost of its template. Keep row templates lean — move heavy logic to computed() Signals or pre-process the data.
scrollToIndex after data changes
If you load new data and want to scroll to a specific item, wait for rendering:
this.items = newData;
// Wait one tick for the viewport to process the new data
setTimeout(() => this.viewport.scrollToIndex(targetIndex));
What's Next
Virtual scrolling renders items efficiently inside a container. But what about elements that need to float above the page — tooltips, dropdowns, dialogs, and menus? The next article covers the CDK Overlay and Portal system, which handles positioning, stacking, and rendering content in a detached DOM layer.