DEV Community

Naresh Rajput
Naresh Rajput

Posted on Edited on

Angular Virtual Scrolling: How It Works, Why We Need It, and How to Implement It

Imagine you are building an application that needs to display 10,000 employees, 50,000 products, or even 100,000 records.

You fetch all the records from an API and display them using Angular's *ngFor.

Everything works fine when you have 20 or 50 records.

But what happens when you have 50,000 records?

Your browser suddenly has to create thousands of HTML elements, manage them, calculate their positions, apply styles, and keep track of changes.

The result?

  • Slow initial rendering.
  • Increased memory consumption.
  • More DOM elements.
  • Poor scrolling performance.
  • A bad user experience, especially on low-end devices.

So, how can we solve this problem?

One solution is Angular Virtual Scrolling.

In this article, we will understand virtual scrolling from the very beginning, explore how it works internally, and implement it in a real Angular application.

Let's get started!


1. First, Understand the Actual Problem

Before understanding virtual scrolling, let's understand what happens when we render a large list normally.

Suppose we have an array containing 10,000 users.

users = Array.from({ length: 10000 }, (_, index) => ({
  id: index + 1,
  name: `User ${index + 1}`
}));
Enter fullscreen mode Exit fullscreen mode

Now, let's display these users using Angular's *ngFor.

<div *ngFor="let user of users">
  <p>{{ user.name }}</p>
</div>
Enter fullscreen mode Exit fullscreen mode

What does Angular do here?

Angular iterates through the array and creates a corresponding view for every item.

For 10,000 users, it creates approximately 10,000 user elements in the DOM.

Important: The browser doesn't just store the text. It also manages HTML elements, their styles, layout, painting, and other rendering-related work.

Now imagine every user row contains:

  • An image.
  • A name.
  • An email address.
  • A status badge.
  • An edit button.
  • A delete button.

The DOM becomes even more complicated.

Why Is This a Problem?

Let's understand it with a simple example.

Imagine you are reading a book containing 1,000 pages.

Would you keep all 1,000 pages open on your desk simultaneously, even though you are currently reading only page 10?

Probably not.

You would keep the current page available and move to the next page when needed.

The same idea applies to virtual scrolling.

Instead of creating every list item in the DOM, we render only the items that are currently visible on the screen, along with a few additional items.

This is the basic idea behind virtual scrolling.


2. What Exactly Is Angular Virtual Scrolling?

Angular Virtual Scrolling is a technique that improves the performance of large lists by rendering only the items needed for the current visible area.

Angular provides this functionality through the Angular CDK (Component Dev Kit).

The important thing to understand is:

Virtual scrolling does not mean that we remove data from our array. It means that we avoid rendering all that data into the DOM at once.

For example:

Suppose we have 10,000 records.

Our browser window can display approximately 10 records at a time.

Without Virtual Scrolling

10,000 records
       |
       v
10,000 DOM elements
       |
       v
Browser manages all 10,000 elements
Enter fullscreen mode Exit fullscreen mode

With Virtual Scrolling

10,000 records
       |
       v
Angular Virtual Scroll
       |
       v
Only visible items + buffer items
       |
       v
A small number of DOM elements
Enter fullscreen mode Exit fullscreen mode

The actual number depends on the viewport height, item size, and buffer configuration.

As the user scrolls, Angular updates the rendered items.

The user feels like they are scrolling through all 10,000 records, but the browser only manages a small portion of them at any given time.

That's the magic of virtual scrolling!


3. How Does Virtual Scrolling Work Internally?

This is probably the most interesting part.

Let's understand what happens behind the scenes.

Virtual scrolling mainly works with three important concepts:

  1. Viewport
  2. Rendered items
  3. Buffer items

A. Viewport

A viewport is the visible area where our list items are displayed.

For example, imagine a container with a height of 500px.

If each item has a height of 50px, we can display approximately 10 items at a time.

+---------------------------+
| User 1                    |
+---------------------------+
| User 2                    |
+---------------------------+
| User 3                    |
+---------------------------+
| User 4                    |
+---------------------------+
| User 5                    |
+---------------------------+
| User 6                    |
+---------------------------+
| User 7                    |
+---------------------------+
| User 8                    |
+---------------------------+
| User 9                    |
+---------------------------+
| User 10                   |
+---------------------------+

       Viewport
       Height = 500px
Enter fullscreen mode Exit fullscreen mode

The viewport is responsible for showing the currently visible portion of the list.

B. Rendered Items

These are the items Angular currently creates and displays in the DOM.

Suppose our viewport displays 10 items.

Angular might render 10 visible items and some additional items around them.

Why?

Because if Angular renders only the 10 visible items, the user might notice a blank area when scrolling quickly.

To prevent this, virtual scrolling uses something called a buffer.

C. Buffer Items

Buffer items are additional items rendered before or after the visible items.

For example:

       Buffer items
       User 11
       User 12

+---------------------------+
| User 13                   |
+---------------------------+
| User 14                   |
+---------------------------+
| User 15                   |
+---------------------------+
| User 16                   |
+---------------------------+
| User 17                   |
+---------------------------+
| User 18                   |
+---------------------------+
| User 19                   |
+---------------------------+
| User 20                   |
+---------------------------+
| User 21                   |
+---------------------------+
| User 22                   |
+---------------------------+

       Viewport
       Visible items

       User 23
       User 24
       Buffer items
Enter fullscreen mode Exit fullscreen mode

The exact number of buffer items depends on the configuration.

When the user scrolls, Angular detects the scroll position and determines which items should be rendered next.

It then removes items that are no longer needed and renders the new ones.

This process continues as the user scrolls.

But What Happens to the Scrollbar?

This is another important question.

If Angular renders only 15 or 20 items, how can the scrollbar represent all 10,000 records?

The answer is that virtual scrolling simulates the total height of the complete list.

Let's calculate it.

Suppose:

  • Total records = 10,000
  • Height of each item = 50px

Total scrollable height:

10,000 × 50 = 500,000px
Enter fullscreen mode Exit fullscreen mode

Angular CDK maintains the appropriate total scrollable size even though all 10,000 elements are not present in the DOM.

It uses a spacer area to represent the space occupied by items that are not currently rendered.

The rendered items are positioned at the correct location within that scrollable area.

So the scrollbar behaves as if the entire list exists.

This is the most important concept to understand: Virtual scrolling separates the total scrollable space from the number of DOM elements currently rendered.


4. Let's Implement Angular Virtual Scrolling

Now that we understand the concept, let's implement it in an Angular application.

We will create a practical example of a user list containing 10,000 records.

We will use Angular CDK.

Step 1: Install Angular CDK

First, install the Angular CDK package.

npm install @angular/cdk
Enter fullscreen mode Exit fullscreen mode

Make sure you use a CDK version compatible with your Angular version.

Step 2: Import the Scrolling Module

If you are using a standalone Angular component, import ScrollingModule directly into the component.

import { Component } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';

@Component({
  selector: 'app-user-list',
  standalone: true,
  imports: [ScrollingModule],
  templateUrl: './user-list.component.html',
  styleUrl: './user-list.component.css'
})
export class UserListComponent {

}
Enter fullscreen mode Exit fullscreen mode

If you are using an NgModule-based application, import ScrollingModule into the relevant module's imports array instead.

Step 3: Create Some Dummy Data

Now let's create an array containing 10,000 users.

import { Component } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';

interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-user-list',
  standalone: true,
  imports: [ScrollingModule],
  templateUrl: './user-list.component.html',
  styleUrl: './user-list.component.css'
})
export class UserListComponent {

  users: User[] = [];

  constructor() {
    this.users = Array.from({ length: 10000 }, (_, index) => ({
      id: index + 1,
      name: `User ${index + 1}`,
      email: `user${index + 1}@example.com`
    }));
  }
}
Enter fullscreen mode Exit fullscreen mode

Here, we are using Array.from() to generate 10,000 user records.

Each user contains:

  • An ID.
  • A name.
  • An email address.

We now have our data ready.

Step 4: Implement Virtual Scrolling in HTML

This is where the actual virtual scrolling happens.

<cdk-virtual-scroll-viewport
  itemSize="60"
  class="user-viewport">

  <div
    class="user-item"
    *cdkVirtualFor="let user of users">

    <h3>{{ user.name }}</h3>
    <p>{{ user.email }}</p>

  </div>

</cdk-virtual-scroll-viewport>
Enter fullscreen mode Exit fullscreen mode

Let's understand each part.

1. cdk-virtual-scroll-viewport

<cdk-virtual-scroll-viewport>
Enter fullscreen mode Exit fullscreen mode

This creates the viewport.

It is the container responsible for managing the virtual scrolling behavior.

2. itemSize

itemSize="60"
Enter fullscreen mode Exit fullscreen mode

This tells Angular CDK that every item has a fixed height of 60 pixels.

Why is this important?

Angular needs to know the size of each item to calculate:

  • How many items can fit inside the viewport.
  • Where the current scroll position is.
  • Which items should be rendered next.
  • How much total scrollable space is required.

For this example, every item must actually occupy 60px in height.

3. cdkVirtualFor

*cdkVirtualFor="let user of users"
Enter fullscreen mode Exit fullscreen mode

This is the virtual scrolling equivalent of *ngFor.

Instead of creating a DOM element for every user, it creates views only for the required portion of the list.

Notice that we are still using our original users array.

We don't need to manually calculate which users should appear on the screen.

Angular CDK handles that for us.

Step 5: Add CSS

Now let's style our viewport and list items.

.user-viewport {
  height: 500px;
  width: 100%;
  border: 1px solid #ddd;
}

.user-item {
  height: 60px;
  box-sizing: border-box;
  padding: 8px 16px;
  border-bottom: 1px solid #eee;
}

.user-item h3 {
  margin: 0;
  font-size: 16px;
}

.user-item p {
  margin: 4px 0 0;
  font-size: 13px;
}
Enter fullscreen mode Exit fullscreen mode

There is something very important here.

Our viewport height is 500px, and each item has a height of 60px.

Therefore, approximately 8 full items can fit inside the viewport.

Also, notice this CSS property:

box-sizing: border-box;
Enter fullscreen mode Exit fullscreen mode

It helps ensure that padding and borders are included within the declared 60px height.

This matters because the itemSize value must match the actual item size.

If you declare itemSize="60" but your rendered item occupies 80px, the virtual scroll calculations can become incorrect.

You may notice blank spaces, overlapping content, or incorrect scrolling behavior.


5. What Happens When We Run This Application?

Let's understand the complete flow.

We have:

Total users = 10,000

Viewport height = 500px

Item height = 60px
Enter fullscreen mode Exit fullscreen mode

Approximately 8 full items can fit inside the viewport.

Angular CDK also renders additional buffer items.

Now imagine the user opens the application.

Initial rendering:

  1. Angular receives the 10,000 users.
  2. The virtual scroll viewport measures its available height.
  3. CDK calculates the required rendered range.
  4. It creates the views for the required items.
  5. The remaining space is represented by the virtual scroll spacer.

When the user scrolls:

  1. The browser reports the scroll position.
  2. CDK calculates the new range of items that should be rendered.
  3. It adds the required new views.
  4. It removes views that are no longer needed.
  5. It positions the rendered content at the correct scroll offset.

This happens continuously as the user scrolls.

The important thing is that Angular doesn't need to keep all 10,000 user elements in the DOM.


6. Understanding Buffer Configuration

Now let's explore something that is useful when working on real-world applications.

Angular CDK provides two important buffer configuration properties:

  • minBufferPx
  • maxBufferPx

You can configure them like this:

<cdk-virtual-scroll-viewport
  itemSize="60"
  minBufferPx="120"
  maxBufferPx="300"
  class="user-viewport">

  <div *cdkVirtualFor="let user of users">
    {{ user.name }}
  </div>

</cdk-virtual-scroll-viewport>
Enter fullscreen mode Exit fullscreen mode

Let's understand both.

minBufferPx

This defines the minimum buffer space that should remain beyond the rendered content in the scrolling direction.

For example:

minBufferPx="120"
Enter fullscreen mode Exit fullscreen mode

This tells CDK to maintain at least approximately 120px of buffer before more items need to be rendered.

maxBufferPx

This defines the target buffer size when CDK decides that more items need to be rendered.

For example:

maxBufferPx="300"
Enter fullscreen mode Exit fullscreen mode

When the buffer drops below the minimum, CDK renders enough additional items to bring the buffer back towards the maximum.

Why do we need this?

Imagine a user scrolling very quickly.

If Angular waits until the visible area is completely empty before rendering more items, the user may see blank spaces.

Buffering helps prevent this.

A simple way to remember:

  • minBufferPx: When should CDK consider rendering more items?
  • maxBufferPx: How much buffer should CDK try to restore?

The right values depend on your item size, scrolling speed, and application performance.


7. Using trackBy With Virtual Scrolling

If you have worked with Angular, you probably know about trackBy.

It helps Angular identify items by a unique key instead of relying only on object references.

We can use it with virtual scrolling too.

trackByUserId(index: number, user: User): number {
  return user.id;
}
Enter fullscreen mode Exit fullscreen mode

Now use it in the template:

<cdk-virtual-scroll-viewport
  itemSize="60"
  class="user-viewport">

  <div
    *cdkVirtualFor="
      let user of users;
      trackBy: trackByUserId
    ">

    {{ user.name }}

  </div>

</cdk-virtual-scroll-viewport>
Enter fullscreen mode Exit fullscreen mode

Why is this useful?

When working with large datasets, identifying items through stable IDs can help Angular manage view updates more efficiently.

It is particularly useful when your data changes frequently.


8. Working With API Data

In real-world applications, we usually don't generate 10,000 users manually.

We get the data from an API.

The good news is that CDK virtual scrolling can work with data received from an API as well.

For example:

import { Component, OnInit } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { HttpClient } from '@angular/common/http';

interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-user-list',
  standalone: true,
  imports: [ScrollingModule],
  templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {

  users: User[] = [];

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get<User[]>('/api/users')
      .subscribe({
        next: (response) => {
          this.users = response;
        },
        error: (error) => {
          console.error('Unable to fetch users', error);
        }
      });
  }
}
Enter fullscreen mode Exit fullscreen mode

For a standalone application, make sure HttpClient is configured using provideHttpClient() in your application providers.

Our HTML remains almost the same:

<cdk-virtual-scroll-viewport
  itemSize="60"
  class="user-viewport">

  <div
    *cdkVirtualFor="let user of users">

    <h3>{{ user.name }}</h3>
    <p>{{ user.email }}</p>

  </div>

</cdk-virtual-scroll-viewport>
Enter fullscreen mode Exit fullscreen mode

The important point here is that virtual scrolling does not require us to change how we fetch data.

We can continue using our existing API services.

However, there is an important distinction.

Virtual scrolling and API pagination are not the same thing.

In this example, we fetch all 10,000 users into memory, but render only a small number of them in the DOM.

If the API returns 1 million records, fetching all of them at once may still be a problem.

In that situation, we may need server-side pagination or incremental data loading along with a suitable virtual scrolling data strategy.

We will understand this difference next.


9. Virtual Scrolling vs Infinite Scrolling vs Pagination

These three concepts are often confused with each other.

Let's understand the difference.

A. Normal Pagination

Imagine an employee management application.

You have 10,000 employees.

Instead of displaying all employees, you display 20 employees per page.

Page 1: Employees 1-20

Page 2: Employees 21-40

Page 3: Employees 41-60
Enter fullscreen mode Exit fullscreen mode

The user clicks Next to load the next page.

This is pagination.

B. Infinite Scrolling

Imagine you are using a social media application.

You scroll through posts.

When you reach the bottom, the application automatically fetches more posts.

Load first 20 posts
       |
       v
User scrolls
       |
       v
Reach bottom
       |
       v
Fetch next 20 posts
       |
       v
Append new posts
Enter fullscreen mode Exit fullscreen mode

This is infinite scrolling.

The previously loaded items generally remain in the DOM unless the application implements its own cleanup strategy.

C. Virtual Scrolling

Now imagine you have 10,000 records already available.

You scroll through them, but the application keeps only the currently needed items in the DOM.

10,000 records
       |
       v
Display visible items
       |
       v
User scrolls
       |
       v
Remove unnecessary DOM items
       |
       v
Render new visible items
Enter fullscreen mode Exit fullscreen mode

This is virtual scrolling.

Comparison

Feature Pagination Infinite Scroll Virtual Scroll
Data loading Usually page by page Usually on demand Can use loaded or incremental data
DOM elements Current page Usually keeps loaded items Only required items
User interaction Click next/previous Scroll to load Scroll normally
Best use case Tables, reports Social feeds Large lists and grids

One important thing to remember:

You can combine infinite loading with virtual scrolling.

For example, you can fetch more data when the user approaches the end of the currently loaded dataset while still keeping the number of DOM elements under control.


10. Where Should We Use Virtual Scrolling in Real Projects?

Now let's look at practical use cases.

1. E-commerce Applications

Imagine an e-commerce website containing 50,000 products.

Each product has an image, name, price, rating, and other details.

Rendering all products at once can be expensive.

Virtual scrolling can render only the products currently needed in the viewport.

Example: Product listing pages with very large datasets.

2. Employee Management Systems

Suppose an admin dashboard contains 20,000 employees.

Users need to scroll through employee names, departments, email addresses, and statuses.

Virtual scrolling can make the list much more efficient.

3. Financial Applications

Imagine a trading application displaying thousands of instruments, transactions, or historical records.

Virtual scrolling can help reduce the DOM workload when displaying large lists.

4. Chat Applications

Some applications have very long conversation histories.

Virtual scrolling can be useful when displaying large collections of messages.

However, chat applications need additional handling for dynamic message heights, reverse scrolling, and maintaining the scroll position.

5. Log Monitoring Dashboards

Imagine a monitoring dashboard receiving thousands of log entries.

Instead of creating thousands of DOM elements, virtual scrolling can keep the rendered portion small.

The general rule is: If your application needs to display a very large collection of items in a scrollable area, virtual scrolling is worth considering.


11. Important Limitations and Things to Remember

Virtual scrolling is useful, but it is not a solution for every situation.

There are some important things you should understand before using it in production.

1. Fixed Item Height

The standard fixed-size virtual scrolling strategy works best when all items have the same height.

For example:

<cdk-virtual-scroll-viewport itemSize="60">
Enter fullscreen mode Exit fullscreen mode

If one item is 60px and another is 120px, the calculations may become incorrect.

Angular CDK has experimental support for variable-size virtual scrolling, but it should not be treated as a production-ready drop-in replacement without checking the current implementation and limitations.

2. Virtual Scrolling Does Not Reduce API Response Size

If you fetch 100,000 records from your backend, all those records may still occupy memory in your application.

Virtual scrolling reduces the number of DOM elements, not the amount of data fetched.

For extremely large datasets, consider server-side pagination or incremental loading.

3. Not Every List Needs Virtual Scrolling

If you have only 20 or 30 records, normal *ngFor is usually enough.

Adding virtual scrolling to every list can introduce unnecessary complexity.

4. Dynamic Content Needs Extra Attention

If your list items contain images, expandable sections, or content that changes their height, you need to consider how that affects item measurements.

5. DOM-Based Testing and Accessibility

Because off-screen items are not necessarily present in the DOM, tests and accessibility interactions should not assume that every record exists in the document at once.

Keyboard navigation, focus management, and screen reader behavior should be tested carefully.

6. DOM Performance Is Not the Only Performance Factor

Virtual scrolling reduces DOM rendering work, but it does not automatically optimize:

  • Complex API calls.
  • Expensive calculations.
  • Large JavaScript objects.
  • Heavy image downloads.
  • Memory-intensive application logic.

You still need to optimize these separately.


12. Bonus: Scroll to a Particular Item Programmatically

Sometimes, we need to scroll directly to a particular item.

For example, suppose we have 10,000 users and want to jump directly to user number 5,000.

Angular CDK provides a method called scrollToIndex().

First, add a template reference:

<cdk-virtual-scroll-viewport
  #viewport
  itemSize="60"
  class="user-viewport">

  <div *cdkVirtualFor="let user of users">
    {{ user.name }}
  </div>

</cdk-virtual-scroll-viewport>
Enter fullscreen mode Exit fullscreen mode

Now use ViewChild:

import { Component, ViewChild } from '@angular/core';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';

export class UserListComponent {

  @ViewChild('viewport')
  viewport!: CdkVirtualScrollViewport;

  scrollToUser(): void {
    this.viewport.scrollToIndex(4999);
  }
}
Enter fullscreen mode Exit fullscreen mode

Add a button:

<button (click)="scrollToUser()">
  Go to User 5000
</button>
Enter fullscreen mode Exit fullscreen mode

Remember that array indexes start from zero.

Therefore, index 4999 represents the 5,000th user.

This is particularly useful in applications where users need to navigate directly to a particular record.


13. Final Thoughts

Let's quickly summarize what we learned.

The biggest problem with displaying large lists is not necessarily the amount of data in the array. It is the amount of work the browser has to perform when creating and managing thousands of DOM elements.

Angular Virtual Scrolling solves this by rendering only the items that are currently required.

We learned:

  • Why rendering thousands of DOM elements can cause performance problems.
  • What virtual scrolling actually means.
  • How viewport, rendered items, and buffer items work.
  • How Angular CDK manages the total scrollable height.
  • How to implement virtual scrolling.
  • How to configure buffer sizes.
  • How to use it with API data.
  • The difference between pagination, infinite scrolling, and virtual scrolling.
  • Where virtual scrolling is useful in real-world applications.
  • Its limitations and important considerations.

My recommendation: Don't use virtual scrolling just because it is available. First understand whether your application actually has a large-list rendering problem. If it does, virtual scrolling can be a very effective solution.

I hope this article helps you understand Angular Virtual Scrolling not just as a feature, but as a performance technique and the problem it solves.

If you found this useful, share your thoughts in the comments!

Happy coding! 🚀


Useful Resources

Top comments (0)