0
0
Angularframework~15 mins

Virtual scrolling for large lists in Angular - Deep Dive

Choose your learning style9 modes available
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.