Virtual Scrolling in Angular: A Comprehensive Guide

Sapna KulSapna Kul
4 min read

Ever thought ?🤔when you keep scolling the instagram/facebook feed, or search for your favourite item on amazon. how this large amount of data is getting loaded so faster without having any performance or lagging issues. The answer lies in the concept of virtual scrolling.

Sometimes we as a developer have to show thousands of elements in a single table. When we add these items to one DOM (Document Object Model), it will impact the performance. We can handle this in many ways like pagination, infinite scroll, and virtual scroll.

Pagination: It helps us to list and show items as chunks it works as expected but we have to click back and forward between pages.

Infinite Scroll: At first, it loads a few items and when we scroll, it appends more items. But when more items keep added, the app is going to slow down.

Enter virtual scrolling, a technique that allows you to display only the items currently in view, thus significantly improving performance and reducing resource consumption. In this guide, we will explore how to implement virtual scrolling in Angular, leveraging the power of the Angular CDK (Component Dev Kit).

What is Virtual Scrolling?

Virtual scrolling is a technique that dynamically loads and unloads items from the DOM based on the user's scroll position. Instead of rendering the entire list of items at once, virtual scrolling creates a "viewport" that only displays the items visible to the user. This approach results in smoother scrolling, faster rendering times, and reduced memory usage compared to traditional methods.

How Virtual Scrolling Works in Angular

At the heart of virtual scrolling in Angular is the Angular CDK's Scrolling module. This module provides the necessary tools to implement virtual scrolling in your Angular applications. The key concept is to use a directive called cdk-virtual-scroll-viewport on an element, turning it into a virtual scrolling container. Within this container, the *cdkVirtualFor directive is used to iterate over the virtual items, dynamically loading and unloading them based on the user's scroll position.

Setting Up a Virtual Scrolling Project in Angular

1. Environment Setup

Ensure that you have the Angular CLI installed on your machine. If not, you can install it using the following command:

npm install -g @angular/cli

Create a new Angular project using the CLI:

ng new virtual-scrolling-demo

cd virtual-scrolling-demo

2. Installing the Virtual Scrolling Module

Install the Angular CDK and Scrolling module:

ng add @angular/cdk

This command installs the necessary dependencies and sets up your project to use the Angular CDK.

Implementing Virtual Scrolling

1. Importing the Scrolling Module

In your Angular module (e.g., app.module.ts), import the Scrolling module:

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

@NgModule({
  declarations: [
    // your components and directives
  ],
  imports: [
    ScrollingModule,
    // other modules
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

2. Using the Virtual Scrolling Directive

Now, let's apply virtual scrolling to a component. In your component's template (e.g., app.component.html), use the cdk-virtual-scroll-viewport directive:

In this example, items is an array of data you want to display, and each item has a fixed height of 50 pixels.

3. Providing Data to Virtual Scrolling

In your component's TypeScript file (e.g., app.component.ts), fetch and bind data to the virtual scrolling component:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  items = []; // Initialize with your data

  constructor() {
    // Fetch data, e.g., from an API
    // Assign the data to the 'items' array
  }
}

Advanced Techniques and Tips

1. Handling Dynamic Data Changes

When your data changes dynamically, you may need to update the virtual scroll. For example, if you add or remove items, you can trigger an update:

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

// ...

export class AppComponent {
  items = [];
  viewport: CdkVirtualScrollViewport;

  constructor() {
    // Fetch data

    // After data changes, update the virtual scroll
    this.viewport.checkViewportSize();
  }
}

2. Optimizing Performance

Optimize performance by adjusting parameters such as item height, buffer size, and other configurations:

Experiment with these values to find the optimal settings for your specific use case.

Real-World Examples

Virtual scrolling is particularly useful when dealing with large datasets, such as infinite-scrolling lists, chat applications, or data tables. Here are a few real-world scenarios where virtual scrolling can make a significant impact on performance and user experience:

  1. Social Media Feeds: Displaying a user's timeline efficiently.

  2. E-commerce Product Lists: Rendering a large catalog of products seamlessly.

  3. Data Tables: Handling large datasets in tables with smooth scrolling.

Conclusion

By leveraging the Angular CDK's Scrolling module, you can implement efficient and performant solutions for rendering large lists of items. Whether you're building a social media feed, an e-commerce platform, or a data table, virtual scrolling can greatly enhance the user experience by providing smooth scrolling and faster rendering times.

Implement virtual scrolling in your Angular projects, experiment with the configurations, and witness the improvement in performance firsthand. Happy coding!

Additional Resources

https://material.angular.io/cdk/scrolling/overview

10
Subscribe to my newsletter

Read articles from Sapna Kul directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sapna Kul
Sapna Kul