Bird
Raised Fist0
Angularframework~15 mins

Virtual scrolling for large lists in Angular - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Virtual scrolling for large lists
What is it?
Virtual scrolling is a technique used to efficiently display very long lists by only rendering the items visible on the screen. Instead of loading all items at once, it dynamically loads and unloads items as the user scrolls. This keeps the app fast and responsive even with thousands of items. Angular provides built-in support for virtual scrolling through its CDK (Component Dev Kit).
Why it matters
Without virtual scrolling, apps that show large lists become slow and use too much memory because they try to render every item at once. This can make the app freeze or crash, especially on slower devices. Virtual scrolling solves this by only showing what the user can see, making the app smooth and fast. This improves user experience and saves device resources.
Where it fits
Before learning virtual scrolling, you should understand basic Angular components, templates, and how lists are rendered with *ngFor. After mastering virtual scrolling, you can explore advanced performance optimizations like infinite scrolling, lazy loading data, and custom scroll strategies.
Mental Model
Core Idea
Virtual scrolling works by showing only the visible part of a large list and reusing DOM elements as the user scrolls, instead of rendering the entire list at once.
Think of it like...
Imagine a long book where you only open and read the pages you need, instead of carrying the whole book open at once. As you turn pages, you put away the old ones and bring new pages into view.
┌─────────────────────────────┐
│       Visible Window         │
│  ┌───────────────────────┐  │
│  │  Rendered Items (few) │  │
│  └───────────────────────┘  │
│                             │
│  ─────────────────────────  │
│  Full List (thousands)       │
│  (Not fully rendered)        │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationRendering lists with *ngFor
🤔
Concept: Learn how Angular normally renders lists using *ngFor directive.
In Angular, you use *ngFor to loop over an array and create DOM elements for each item. For example,
{{item}}
creates one div per item. This works well for small lists but renders all items at once.
Result
All items in the list appear on the page, which can slow down the app if the list is very long.
Understanding how Angular renders lists by default helps see why rendering thousands of items causes performance issues.
2
FoundationPerformance issues with large lists
🤔
Concept: Recognize the problem of rendering large lists fully in the DOM.
When you have thousands of items, Angular creates thousands of DOM elements. This uses a lot of memory and slows down rendering and scrolling. The browser struggles to keep up, causing lag and poor user experience.
Result
The app becomes slow, unresponsive, or even crashes on devices with limited resources.
Knowing the limits of full rendering motivates the need for smarter techniques like virtual scrolling.
3
IntermediateHow virtual scrolling works in Angular CDK
🤔Before reading on: do you think virtual scrolling renders all items but hides some, or only renders visible items? Commit to your answer.
Concept: Angular CDK virtual scrolling renders only the visible items plus a small buffer, updating them as the user scrolls.
Angular's CDK virtual scroll viewport creates a fixed-size container that shows a small subset of items. As you scroll, it recycles DOM elements by changing their data instead of creating new ones. This keeps the DOM light and fast.
Result
Only a few items are in the DOM at any time, making scrolling smooth and fast even for huge lists.
Understanding that virtual scrolling recycles elements rather than hiding them explains why it saves so much memory and improves performance.
4
IntermediateSetting up Angular CDK virtual scroll
🤔Before reading on: do you think you need to write complex code to use virtual scrolling, or is it mostly configuration? Commit to your answer.
Concept: Learn how to enable virtual scrolling using Angular CDK with minimal code changes.
First, install @angular/cdk. Then import ScrollingModule in your module. Replace *ngFor with and use *cdkVirtualFor instead of *ngFor. Set itemSize to the height of each item in pixels. Example:
{{item}}
Result
The list now only renders visible items inside a scrollable container, improving performance.
Knowing that virtual scrolling is mostly a configuration change lowers the barrier to adopting it in real projects.
5
IntermediateHandling dynamic item sizes
🤔Before reading on: do you think virtual scrolling can handle items with different heights out of the box? Commit to your answer.
Concept: Explore how virtual scrolling deals with items that have varying heights and the challenges involved.
By default, Angular CDK virtual scroll assumes fixed item sizes for smooth calculation. For dynamic sizes, you can use autosize strategy or manually measure items, but this adds complexity and may reduce performance. The autosize strategy recalculates viewport size as items render.
Result
Virtual scrolling can work with dynamic sizes but requires extra setup and may be less efficient.
Understanding the fixed size assumption clarifies why virtual scrolling is simplest with uniform item heights.
6
AdvancedIntegrating virtual scroll with infinite loading
🤔Before reading on: do you think virtual scrolling automatically loads more data when scrolling reaches the end? Commit to your answer.
Concept: Learn how to combine virtual scrolling with loading more data on demand (infinite scroll).
Virtual scrolling only manages rendering visible items. To load more data, you listen to scroll events or use the viewport's scrolledIndexChange observable. When near the end, trigger a data fetch and append items to the list. This keeps the list growing smoothly without loading all data upfront.
Result
Users can scroll through huge or endless lists without performance drops or waiting for all data to load.
Knowing that virtual scrolling and infinite loading are separate but complementary helps design scalable list experiences.
7
ExpertPerformance tuning and pitfalls in production
🤔Before reading on: do you think adding virtual scrolling always guarantees perfect performance? Commit to your answer.
Concept: Understand advanced performance considerations and common mistakes when using virtual scrolling in real apps.
Virtual scrolling improves rendering but can still suffer if items have complex templates, heavy bindings, or frequent change detection. Use OnPush change detection, trackBy functions, and avoid unnecessary DOM updates. Also, watch out for scroll jank caused by large buffers or slow data fetching. Profiling with browser DevTools helps find bottlenecks.
Result
With tuning, virtual scrolling delivers smooth, fast scrolling even in complex real-world apps.
Knowing virtual scrolling is a tool, not a silver bullet, prevents overconfidence and encourages holistic performance optimization.
Under the Hood
Angular CDK virtual scroll creates a fixed-height viewport container and calculates which items should be visible based on scroll position. It renders only those items and reuses DOM elements by updating their data context as the user scrolls. This recycling avoids creating and destroying many DOM nodes, reducing memory and CPU usage. The viewport manages scroll height to match the full list size, creating a natural scrollbar.
Why designed this way?
This design balances performance and simplicity. Rendering all items is too slow and memory-heavy. Rendering only visible items reduces load but requires careful DOM management. Recycling DOM nodes avoids costly creation/destruction cycles. Fixed item size assumptions simplify calculations and improve smoothness. Alternatives like full rendering or manual DOM management were less efficient or more complex.
┌───────────────────────────────┐
│       Virtual Scroll Viewport  │
│ ┌───────────────────────────┐ │
│ │  Visible Items Rendered    │ │
│ │  (Recycled DOM Elements)   │ │
│ └───────────────────────────┘ │
│                               │
│  Scrollbar represents full list│
│  height but only visible items │
│  are in DOM                   │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does virtual scrolling render all list items but hide some? Commit yes or no.
Common Belief:Virtual scrolling renders all items but just hides the ones not visible.
Tap to reveal reality
Reality:Virtual scrolling only renders the visible items plus a small buffer, not the entire list.
Why it matters:Believing all items are rendered leads to misunderstanding performance benefits and may cause unnecessary optimizations.
Quick: Can virtual scrolling handle items of any height without extra work? Commit yes or no.
Common Belief:Virtual scrolling works perfectly with items of varying heights out of the box.
Tap to reveal reality
Reality:Virtual scrolling assumes fixed item heights by default; dynamic heights require extra setup and can reduce performance.
Why it matters:Ignoring this can cause layout glitches or poor scrolling experience in apps with variable item sizes.
Quick: Does virtual scrolling automatically load more data when scrolling? Commit yes or no.
Common Belief:Virtual scrolling automatically fetches more data as you scroll to the end.
Tap to reveal reality
Reality:Virtual scrolling only manages rendering; loading more data must be implemented separately.
Why it matters:Expecting automatic data loading can cause incomplete lists or broken user experience.
Quick: Is virtual scrolling a guaranteed fix for all list performance issues? Commit yes or no.
Common Belief:Using virtual scrolling always makes list rendering perfectly smooth and fast.
Tap to reveal reality
Reality:Virtual scrolling helps but complex templates, heavy bindings, or poor change detection can still cause lag.
Why it matters:Overreliance on virtual scrolling alone may lead to ignoring other important performance optimizations.
Expert Zone
1
Virtual scrolling's fixed item size assumption is a tradeoff for smoothness; handling dynamic sizes often requires custom strategies or third-party libraries.
2
Using trackBy functions with *cdkVirtualFor is critical to prevent unnecessary DOM updates and improve performance.
3
The buffer size around visible items affects perceived smoothness and memory use; tuning it balances responsiveness and resource consumption.
When NOT to use
Avoid virtual scrolling when list items are very few or when items have highly dynamic sizes that cannot be approximated. For very complex item layouts or when SEO requires all items in DOM, consider pagination or server-side rendering instead.
Production Patterns
In real apps, virtual scrolling is combined with infinite scrolling to load data on demand, OnPush change detection for performance, and trackBy functions to minimize DOM churn. Developers also profile scroll performance and tune buffer sizes. Sometimes, custom scroll strategies or third-party libraries extend CDK capabilities for dynamic item sizes.
Connections
Pagination
Alternative approach to handling large lists by splitting data into pages instead of scrolling.
Understanding pagination helps appreciate virtual scrolling as a continuous, smooth alternative that avoids page reloads.
Memory management in operating systems
Both virtual scrolling and OS memory management use the idea of loading only what is needed into active space.
Knowing how OS swaps memory pages in and out helps understand why virtual scrolling loads only visible items to save resources.
Lazy loading in web development
Virtual scrolling builds on the lazy loading principle by delaying rendering until items are needed.
Recognizing lazy loading patterns clarifies how virtual scrolling improves performance by deferring work.
Common Pitfalls
#1Not setting itemSize correctly causes wrong scroll height and glitches.
Wrong approach:
{{item}}
Correct approach:
{{item}}
Root cause:Misunderstanding that itemSize must match the pixel height of each item for correct calculations.
#2Using *ngFor inside virtual scroll instead of *cdkVirtualFor causes full rendering.
Wrong approach:
{{item}}
Correct approach:
{{item}}
Root cause:Confusing Angular's *ngFor with the special *cdkVirtualFor directive needed for virtual scrolling.
#3Not using trackBy function leads to unnecessary DOM updates and poor performance.
Wrong approach:
{{item.name}}
Correct approach:
{{item.name}}
trackById(index, item) { return item.id; }
Root cause:Ignoring Angular's change detection optimization that requires trackBy to identify items uniquely.
Key Takeaways
Virtual scrolling improves app performance by rendering only the visible items in large lists, reducing memory and CPU usage.
Angular CDK provides an easy way to implement virtual scrolling with the and *cdkVirtualFor directive.
Virtual scrolling assumes fixed item sizes for smooth scrolling; handling dynamic sizes requires extra work and may impact performance.
Combining virtual scrolling with infinite loading and change detection optimizations creates scalable, smooth user experiences.
Understanding virtual scrolling's internal recycling mechanism helps avoid common mistakes and tune performance in real-world apps.

Practice

(1/5)
1. What is the main benefit of using cdk-virtual-scroll-viewport in Angular for large lists?
easy
A. It renders only visible items to improve performance.
B. It automatically sorts the list items alphabetically.
C. It adds animations to list items when scrolling.
D. It duplicates list items for faster loading.

Solution

  1. Step 1: Understand virtual scrolling purpose

    Virtual scrolling aims to improve performance by rendering only the visible items in a large list.
  2. Step 2: Identify cdk-virtual-scroll-viewport role

    This Angular component implements virtual scrolling by showing only the items visible in the viewport, reducing DOM load.
  3. Final Answer:

    It renders only visible items to improve performance. -> Option A
  4. Quick Check:

    Virtual scrolling = render visible items only [OK]
Hint: Virtual scroll shows visible items only to boost speed [OK]
Common Mistakes:
  • Thinking it sorts or animates items
  • Assuming it duplicates items for speed
  • Confusing with pagination
2. Which of the following is the correct way to use virtual scrolling in Angular template?
easy
A. <cdk-virtual-scroll-viewport><div *cdkVirtualFor="let item in items">{{item}}</div></cdk-virtual-scroll-viewport>
B. <cdk-virtual-scroll-viewport itemSize="50"><div *ngFor="let item of items">{{item}}</div></cdk-virtual-scroll-viewport>
C. <cdk-virtual-scroll-viewport itemSize="50"><div *cdkVirtualFor="let item of items">{{item}}</div></cdk-virtual-scroll-viewport>
D. <cdk-virtual-scroll-viewport itemSize="50"><div *ngFor="let item in items">{{item}}</div></cdk-virtual-scroll-viewport>

Solution

  1. Step 1: Identify correct directive for virtual scroll

    Angular CDK virtual scroll requires *cdkVirtualFor instead of *ngFor to render visible items only.
  2. Step 2: Check syntax and itemSize usage

    The itemSize attribute is required on cdk-virtual-scroll-viewport to set fixed item height for scrolling calculations.
  3. Final Answer:

    <cdk-virtual-scroll-viewport itemSize="50"><div *cdkVirtualFor="let item of items">{{item}}</div></cdk-virtual-scroll-viewport> -> Option C
  4. Quick Check:

    Use *cdkVirtualFor with itemSize on viewport [OK]
Hint: Use *cdkVirtualFor, not *ngFor, inside cdk-virtual-scroll-viewport [OK]
Common Mistakes:
  • Using *ngFor instead of *cdkVirtualFor
  • Using 'let item in items' instead of 'of'
  • Omitting itemSize attribute
3. Given this Angular template snippet:
<cdk-virtual-scroll-viewport itemSize="40" style="height: 120px;">
  <div *cdkVirtualFor="let item of items">{{item}}</div>
</cdk-virtual-scroll-viewport>

and items = ['A', 'B', 'C', 'D', 'E'], how many items will be visible at once?
medium
A. 3 items
B. 5 items
C. 2 items
D. 4 items

Solution

  1. Step 1: Calculate viewport height in pixels

    The viewport height is set to 120px.
  2. Step 2: Divide viewport height by itemSize

    Each item is 40px tall, so 120px / 40px = 3 items visible at once.
  3. Final Answer:

    3 items -> Option A
  4. Quick Check:

    Visible items = viewport height / itemSize = 3 [OK]
Hint: Divide viewport height by itemSize to find visible items [OK]
Common Mistakes:
  • Counting all items instead of visible ones
  • Ignoring style height on viewport
  • Using wrong division operator
4. What is wrong with this Angular virtual scroll code?
<cdk-virtual-scroll-viewport itemSize="50">
  <div *cdkVirtualFor="let item in items">{{item}}</div>
</cdk-virtual-scroll-viewport>
medium
A. The *cdkVirtualFor directive must be on the viewport, not the div.
B. Missing style height on viewport causes no scroll.
C. itemSize must be a number, not a string.
D. Using *cdkVirtualFor with 'in' instead of 'of' causes an error.

Solution

  1. Step 1: Check syntax of *cdkVirtualFor directive

    The correct syntax uses 'of' to iterate over items, not 'in'. Using 'in' causes a template error.
  2. Step 2: Verify other attributes

    itemSize can be a string representing a number, and style height is recommended but not syntax error. The directive must be on the repeated element, not viewport.
  3. Final Answer:

    Using *cdkVirtualFor with 'in' instead of 'of' causes an error. -> Option D
  4. Quick Check:

    *cdkVirtualFor uses 'of', not 'in' [OK]
Hint: Use 'of' with *cdkVirtualFor, not 'in' [OK]
Common Mistakes:
  • Using 'in' instead of 'of' in *cdkVirtualFor
  • Forgetting to set viewport height
  • Placing directive on wrong element
5. You want to display a list of 10,000 items with virtual scrolling. Which combination of settings ensures smooth scrolling and correct rendering?
hard
A. Use *ngFor inside a scrollable div without cdk-virtual-scroll-viewport.
B. Use cdk-virtual-scroll-viewport with fixed itemSize, set viewport height, and use *cdkVirtualFor.
C. Use cdk-virtual-scroll-viewport with variable itemSize and *cdkVirtualFor.
D. Use cdk-virtual-scroll-viewport without itemSize, and *ngFor for rendering.

Solution

  1. Step 1: Understand virtual scroll requirements

    Virtual scrolling requires a fixed itemSize to calculate visible items and smooth scrolling.
  2. Step 2: Use correct directives and styles

    Use cdk-virtual-scroll-viewport with a fixed height and *cdkVirtualFor to render only visible items efficiently.
  3. Step 3: Avoid common pitfalls

    Not setting itemSize or using *ngFor causes performance issues or errors.
  4. Final Answer:

    Use cdk-virtual-scroll-viewport with fixed itemSize, set viewport height, and use *cdkVirtualFor. -> Option B
  5. Quick Check:

    Fixed itemSize + *cdkVirtualFor + viewport height = smooth scroll [OK]
Hint: Fixed itemSize and *cdkVirtualFor are key for smooth virtual scroll [OK]
Common Mistakes:
  • Omitting itemSize or viewport height
  • Using *ngFor instead of *cdkVirtualFor
  • Trying variable item sizes without special handling