Handle large data sets in angular with virtual scrolling

Gili Yaniv
4 min readOct 9, 2024

--

When building web applications with Angular, performance optimization is key to ensuring a smooth user experience. One challenge developers often face is efficiently rendering large lists of data on the screen without compromising performance. As the dataset grows, a straightforward approach like using *ngFor to loop through and display all items can result in significant performance bottlenecks. This is where virtual scrolling comes into play.

In this blog post, we’ll discuss what virtual scrolling is, how to implement it in an Angular application, and when it should be used over a traditional *ngFor.

What is Virtual Scrolling?

Virtual scrolling is a technique that only renders the visible items in a list at any given time, rather than rendering the entire list. As the user scrolls, new items are rendered while the items that move out of the viewport are removed from the DOM. This results in a significant performance boost, especially when dealing with very large datasets.

By only rendering a subset of items at a time, the browser has to handle fewer DOM elements, which can greatly reduce the memory and CPU usage of your application.

Key Benefits of Virtual Scrolling:

1. Improved Performance: Only the visible portion of the data is rendered.
2. Efficient DOM Updates: Angular keeps track of what is visible, so DOM manipulations are reduced.
3. Reduced Memory Usage: Since not all elements are loaded into the DOM, the application uses less memory.

When to Use Virtual Scrolling

Virtual scrolling is particularly useful when dealing with:
- Large Lists or Grids: If you have thousands or even millions of items in your list, rendering them all at once can cause your application to freeze or become sluggish.
- Lazy Loading Data: When you don’t need to load all data at once and can afford to load it as the user scrolls.
- Dynamic Data Sources: Data that frequently changes (like in chat applications or live feeds) benefit from virtual scrolling since it helps optimize resource usage.

Scenarios Where Virtual Scrolling Excels:
- Product catalog pages with hundreds or thousands of products.
- Infinite scrolling social media feeds.
- Data tables with a large number of rows.
- File explorers and folder structures.

How to Implement Virtual Scrolling in Angular

Angular offers the CDK (Component Dev Kit) as part of the Angular Material package, which provides a straightforward way to implement virtual scrolling. To get started with virtual scrolling, follow these steps:

Step 1: Install Angular CDK
To use virtual scrolling, you need to install the Angular CDK package if you haven’t already:

npm install @angular/cdk

Step 2: Import ScrollingModule
Once installed, import the ScrollingModule into your Angular module:

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

@NgModule({
declarations: [/* your components */],
imports: [
ScrollingModule,
// other imports
],
bootstrap: [/* root component */],
})
export class AppModule {}

Step 3: Use `cdk-virtual-scroll-viewport` in the Template

In the template, replace the *ngFor loop with a `cdk-virtual-scroll-viewport` to enable virtual scrolling:

<cdk-virtual-scroll-viewport itemSize="50" class="example-viewport">
<div *cdkVirtualFor="let item of items" class="example-item">
{{item}}
</div>
</cdk-virtual-scroll-viewport>

Here, `itemSize` defines the size of each item in pixels. The `cdkVirtualFor` directive functions similarly to *ngFor, but only renders the visible items.

Step 4: Styling the Virtual Scroll

You can style the scroll container to specify its height and layout:

example-viewport {
height: 400px;
width: 100%;
overflow: auto;
}
.example-item {
height: 50px;
border-bottom: 1px solid #ccc;
display: flex;
align-items: center;
padding: 0 10px;
}

Now, the list will only render items that fit within the `400px` height, improving performance by reducing the number of DOM elements.

When is Regular `*ngFor` Enough?

While virtual scrolling is a powerful tool, it’s not always necessary. In some scenarios, using a regular `*ngFor` loop is sufficient and can simplify your code.

Use `*ngFor` When:
1. The List is Small: If you’re dealing with a small number of items (e.g., less than 100), virtual scrolling may be overkill. The browser can easily handle a small number of DOM elements, and the additional complexity of implementing virtual scrolling won’t offer much benefit.
2. Simple Applications: For simple, static lists that don’t have significant performance issues, *ngFor is easier to implement and maintain.
3. No Scrollable Container: In cases where all data fits on the screen without the need for scrolling, virtual scrolling would be unnecessary.

For example, a list of navigation links in a sidebar, or a dropdown with fewer than 50 options, can use `*ngFor` without noticeable performance degradation.

When Regular `*ngFor` Can Be Used:

- Displaying a limited number of categories in a sidebar.
- Showing a list of recent comments or notifications (if the list is small).
- Rendering short dropdowns or form options.

Conclusion

Virtual scrolling is a powerful technique that can vastly improve the performance of an Angular application when dealing with large datasets. It reduces the burden on the browser by only rendering what is visible to the user at any given time. However, for smaller lists or simpler use cases, regular `*ngFor` is often sufficient and easier to manage.

Understanding when to use virtual scrolling versus a traditional `*ngFor` comes down to the size of the dataset and the performance requirements of your application. By making the right choice, you can strike a balance between performance and simplicity in your Angular projects.

Happy coding!

Follow me on Twitter, Medium, and Linkedin to read more!

--

--

No responses yet