Angular 7 – Implement Infinite Virtual Scroll in Few Easy Steps in Latest Angular 7.x

In this post, we will discuss one of the major updates in Angular 7 version, its new Virtual scroll feature in CDK which is Material Component Development Kit. Virtual scrolling comes into action where we have a long list of item in applications, the performance of page decreases due to lots of hidden HTML data which are of no use.

Virtual scrolling improves the performance of pages by dynamically rendering only that list data which is visible to the user, as a user scrolls the current set of items replaced by new giving a glimpse of a continuous traditional list.

Let’s get started and create Angular 7 Application with an Infinite virtual scroll.

Also, check Drag and Drop implementation in Angular Material 7

Create new Angular 7 App

We will use Angular CLI to create an application, for that you must have the latest version installed

Run following to create a new app

After running this, CLI will ask for routing and style sheet format. This confirmation is introduced in the latest CLI version.

If you have Visual Studio Code( VS Code ) installed, run following to open in the project in VS Code

Open application server on the browser.

Virtual Scrolling Module

To implement Virtual Scrolling, We need to install Angular CDK package and import  ScrollingModule in the application module.

After the successful install, we will import ScrollingModule in app.module.ts

HTML list directive

Now add Virtual Scroll list directive in app.component.html

Here we are implementing virtual scroll, cdk-virtual-scroll-viewport component provides a viewport for virtual scrolling, it must have a property itemSize to define the height of each item in pixels in our virtual list. *cdkVirtualFor is similar to *ngFor and used to loop over the list of object.

There are many other parameters for this directive:

cdkVirtualForTemplate: The template used to stamp out new elements.
cdkVirtualForTrackBy: TheTrackByFunction to use for tracking changes.
viewChange: Emits when the rendered view of the data changes.
Check more supported emit event in the documentation here

In app.component.ts, paste this code

Here we used the faker.js module to generate dummy data of 1000 value object.

You can install faker.js in Angular by running following commands

List Item Styling & Animation

We must provide height to cdk-virtual-scroll-viewport and items we are going to show in scroll list, the specified height of viewport and item is required by the component to decide whether to remove or show current item.

Add following in app.component.scss and some additional styling for make cute list 😛

Scroll effect lightSpeedIn is used from Animate.css

It’s Done! now run the app running below command

to see it in action. Check working demo here.

Also, check Drag and Drop implementation in Angular Material 7

Leave a Reply

avatar
  Subscribe  
Notify of