Angular Virtual Scrolling is one of the game-changer features to deal with extensive lists of items. In this guide, we will discuss Angular Virtual Scrolling focusing on the Angular CDK Virtual Scroll package and its core component, cdk-virtual-scroll-viewport. Moreover, we will add the required animations using CSS to make it look more awesome in your application.
[lwptoc]
What is Virtual Scrolling?
Let’s understand more about Virtual Scrolling and how it works. In applications, to display long lists of data like table rows, traditionally all the items are rendered at once. This proves sluggish and impacts the performance due to loads of DOM elements and consumption of resources at the web browser level.
Angular Virtual Scrolling seamlessly address this issue dynamically rendering only the items that need to be visible on the screen. As the user scrolls to view new items, the older items keep on being replaced by new ones. In this way, users don’t notice anything unusual and the performance is enhanced greatly.
Adding Virtual Scrolling in Angular Application using CDk
Let’s follow these easy steps to start by integrating Virtual Scroll on Lists in Angular. Thereafter, we will also add Virtual Scrolling on the Table.
1. Setting Up Your Angular Application
2. Integrating Virtual Scrolling with Angular CDK
3. Add Faker Js Library
4. Add Bootstrap for Styling
5. Implementing the Virtual Scroll Component
6. Styling and Animation
7. Running the Application
1. Setting Up Your Angular Application
To begin implementing Angular Virtual Scrolling, we will create a new Angular project to ease the process. You can follow these steps:
Install Angular CLI
Make sure you have the latest version of Angular CLI installed globally:
npm install -g @angular/cli
Create a New Angular App
Now create a new Angular application using Angular CLI:
ng new virtual-scroll-demo
Navigate to the Project Folder
Move into your newly created project folder:
cd virtual-scroll-demo
If using Visual Studio Code, you can open the project by executing below command:
code .
2. Integrating Virtual Scrolling with Angular CDK
Angular Component Development Kit or CDK offers a wide range of tools for building components usefull components. We will use the Virtual Scrolling provided by the Angular CDK package. Let’s set it up:
Install Angular CDK Package
Install the Angular CDK package into the Angular project:
npm install @angular/cdk@latest
This package provides the necessary tools for Virtual Scrolling.
Import ScrollingModule
Thereafter, In the Angular main component file app.module.ts, we will import the ScrollingModule
from @angular/cdk/scrolling
and the PlatformModule
from @angular/cdk/platform
required for Virtual Scrolling:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { PlatformModule } from '@angular/cdk/platform';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ScrollingModule,
PlatformModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
3. Add Faker Js Library (Optional)
We will use the Faker Js library, which will help to generate fake data for Virtual Loading lists. Following are the easy steps to install and use in ES project components like Angular:
Execute the following npm command to install the Faker Js as a dev dependency in your project:
npm install --save-dev @faker-js/faker
Thereafter, you will be able to simply import it as shown below:
import { faker } from '@faker-js/faker';
We have used Faker to get data, but this step is optional if you are using any static or dynamic data for your application.
4. Add Bootstrap for Styling
We will install the Bootstrap library, to help us easily style our application without adding any custom CSS styles. This step is optional and depends on our application UI libraries’ styling configurations.
Execute following command to install the Bootstrap package:
npm install bootstrap
After the bootstrap package is installed, you can update the styles
array inside the angular.json file to include bootstrap.min.css as shown below:
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
5. Implementing the Virtual Scroll Component
The Angular Virtual Scrolling is created by adding the cdk-virtual-scroll-viewport
component. This component works as a viewport for virtual scrolling and requires a few essential attributes to operate correctly.
HTML List Directive
In our component’s HTML file for example app.component.html, we will add the cdk-virtual-scroll-viewport
component to enable virtual scrolling:
<cdk-virtual-scroll-viewport itemSize="100">
<div class="list-group">
<a href="#" class="list-group-item list-group-item-action animated lightSpeedIn item-wrap"
*cdkVirtualFor="let p of dummydata;">
<div class="d-flex w-100 justify-content-between">
<div class="thumbnail-wrap" style="width:150px" >
<img [src]="p.avatar" class="img-fluid rounded-circle" alt="{{p.name}}" />
</div>
<div class="info-wrap">
<h4 class="mb-1">{{p.name}}</h4>
<h6 class="text-muted">{{p.company}}</h6>
</div>
</div>
</a>
</div>
</cdk-virtual-scroll-viewport>
Here we use used few of the required properties:
itemSize
: This property defines the height of each item in the virtual list which is its height in px.
*cdkVirtualFor
: Similar to *ngFor
, this directive loops over a list of items and dynamically renders them within the viewport as the list is scrolled.
Populating Data
Now we will update the app.component.ts file to populate the list by fetching the data from API. Here we are generating dummy data using the Faker.js library:
import { Component } from '@angular/core';
import { faker } from '@faker-js/faker';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'virtual-scroll-demo';
dummydata;
constructor() {
this.dummydata = Array(10000)
.fill(1)
.map((_) => {
return {
name: faker.person.fullName(),
company: faker.company.name(),
avatar: faker.image.avatar(),
};
});
}
}
6. Styling and Animation
In our example app, we will add some Styling in addition to Animation that will help use to easily identify the newly added items to the list. It also enhances the user experience for the virtual scroll.
SCSS Styling
cdk-virtual-scroll-viewport {
height: 100vh;
}
Animation
Here we have added the animation to our list of items to make them visually appealing. In this example, we use the @keyframes
animation named fade-in
:
@-webkit-keyframes lightSpeedIn {
from {
-webkit-transform: translate3d(100%, 0, 0) skewX(-30deg);
transform: translate3d(100%, 0, 0) skewX(-30deg);
opacity: 0
}
60% {
-webkit-transform: skewX(20deg);
transform: skewX(20deg);
opacity: 1
}
80% {
-webkit-transform: skewX(-5deg);
transform: skewX(-5deg)
}
to {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0)
}
}
@keyframes lightSpeedIn {
from {
-webkit-transform: translate3d(100%, 0, 0) skewX(-30deg);
transform: translate3d(100%, 0, 0) skewX(-30deg);
opacity: 0
}
60% {
-webkit-transform: skewX(20deg);
transform: skewX(20deg);
opacity: 1
}
80% {
-webkit-transform: skewX(-5deg);
transform: skewX(-5deg)
}
to {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0)
}
}
.lightSpeedIn {
-webkit-animation-name: lightSpeedIn;
animation-name: lightSpeedIn;
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out
}
.animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both
}
7. Running the Application
Finally, we are ready to see our Angular application with Virtual Scrolling in action. Execute following command to run the webserver and open the application in w browser tab:
ng serve --open
Now you will be able to see the Virtual Scrolling list that we create in the CDK library. You will experience how the items are getting rendered in the viewport even if they are as huge as 10000 without any performance hit on the browser.
Conclusion
We have implemented the Angular Virtual Scrolling which is powered by the Angular CDK. We used its cdk-virtual-scroll-viewport
component to create fully optimized and performance-efficient extensive lists of data. Virtual Scrolling can be implemented at any UI component like Lists, Table, Selectboxes etc. to make them work efficiently without performance lagging.
Virtual Scrolling only helps if the number of rows that need to be rendered are very huge, as in such case the CDK component can help to control the visible set of items by easily managing the DOM items instead of dummy all items at once.
Leave a Reply