typescript 45 lines · 6 steps

Virtual scrolling a contact list in Angular

An OnPush standalone component renders thousands of contacts efficiently by combining the CDK virtual scroll viewport with a signal.

Explained by highlit
1import { Component, ChangeDetectionStrategy, inject, signal } from '@angular/core';
2import { CommonModule } from '@angular/common';
3import { ScrollingModule } from '@angular/cdk/scrolling';
4import { toObservable } from '@angular/core/rxjs-interop';
5import { ContactService, Contact } from './contact.service';
6 
7@Component({
8 selector: 'app-contact-list',
9 standalone: true,
10 changeDetection: ChangeDetectionStrategy.OnPush,
11 imports: [CommonModule, ScrollingModule],
12 styles: [`
13 .viewport { height: 480px; width: 320px; }
14 .row {
15 display: flex;
16 align-items: center;
17 gap: 12px;
18 height: 56px;
19 padding: 0 16px;
20 border-bottom: 1px solid var(--divider);
21 }
22 .avatar { width: 32px; height: 32px; border-radius: 50%; }
23 .name { font-weight: 500; }
24 .email { color: var(--muted); font-size: 0.85rem; }
25 `],
26 template: `
27 <cdk-virtual-scroll-viewport itemSize="56" minBufferPx="280" maxBufferPx="560" class="viewport">
28 <div *cdkVirtualFor="let contact of contacts(); trackBy: trackById" class="row">
29 <img class="avatar" [src]="contact.avatarUrl" [alt]="contact.name" loading="lazy" />
30 <div>
31 <div class="name">{{ contact.name }}</div>
32 <div class="email">{{ contact.email }}</div>
33 </div>
34 </div>
35 </cdk-virtual-scroll-viewport>
36 `,
37})
38export class ContactListComponent {
39 private readonly contactService = inject(ContactService);
40 readonly contacts = signal<Contact[]>(this.contactService.getAll());
41 
42 trackById(_index: number, contact: Contact): string {
43 return contact.id;
44 }
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1CDK virtual scrolling renders only the visible window, so list size stops dictating DOM cost.
  2. 2A signal reads cleanly under OnPush change detection, making template updates explicit and cheap.
  3. 3A trackBy keyed on stable identity is what lets recycled rows update without full re-creation.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Virtual scrolling a contact list in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code