We're hiring
Products

Channels

Beams

Chatkit

DocsTutorialsSupportCareersPusher Blog
Sign InSign Up
Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Sign InSign Up

Building infinite virtual scrolling lists with the new Angular 7 CDK

  • Lotanna Nwose
April 1st, 2019
You will need Node and the Angular 7 CLI installed on your machine.

TL;DR:In this tutorial, we will learn about and take a good look at how to use the infinite virtual scroll tool in the Angular Material Component Development Kit.

Introduction

Angular is a JavaScript (TypeScript) framework for building web applications, mobile or desktop with over 42,000 stars️ on GitHub. It is maintained by the Angular team at Google and a host of community members and organizations. Angular version 7.0 was released some months ago. One of the features it shipped with is the virtual scroll tool in the Component Development Kit.

Component Development Kit (CDK)

The Component Development Kit is a set of tools that implement common behaviors and components with very unique interaction styles without being opinionated about the template choices. It is a kind of abstraction of the Angular Material Library, with no styling specific to material design. It provides more unique ways to get creative while building your Angular components.

Understanding the process

Most times when we work with really long lists in our presentation layer in Angular, we think of additional features to make the experience better. This can be like adding pagination or “next” button or even a “load more” button. The Component Development Kit has a scrolling feature that now helps us to have a better and more dynamic way of rendering these long lists of items in a way that is most efficient and with the lowest cost.

What you will learn

By building different fragments of a long list in this tutorial with the virtual scrolling CDK you will learn how to use basic best practises of using Angular and the Component Development Kit to build dynamic lists that will load and remove list items from the DOM just by scrolling. You get to see only the subset of the list you want to see at a particular time both on your frontend and in the DOM.

Prerequisites

To be able to follow through in this article’s demonstration you should have:

  • Node version 11.0 installed on your machine.
  • Node Package Manager version 6.7 (usually ships with Node installation).
  • Angular CLI version 7.0
  • The latest version of Angular (version 7)
    // run the command in a terminal
    ng version

Confirm that you are using version 7, and update to 7 if you are not. Other things that will be nice-to-haves are:

  • A working knowledge of the Angular framework at a beginner level.
  • Familiarity with Angular services will be a plus but not a requirement.

Setting up

We will go through the process of setting up the development environment and installing all the required dependencies for the Component Development Kit to work.

Generating an Angular 7 application

    //cd to a preferred location
    // run the command below
    ng new virtualscroll

You do not need Angular routing, but you have to choose CSS for styling. Now, we get Angular Material installed on the above app

    ng add @angular/material

You can choose any pre-built theme of your choice or create one yourself (we used indigo-pink). For this tutorial, you do not need HammerJs or the Animations module. Angular Material ships with the Component Development Kit where our virtual scrolling module is located. Then, import the scrolling module in the app module so it is available for use in the Angular application so that the import section will look like so:

    // src/app/app.module.ts
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { ScrollingModule } from '@angular/cdk/scrolling'
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { ArtistsComponent } from './artists/artists.component';

Add this the scrolling module to the import section so it would look like this:

    imports: [BrowserModule,
             ScrollingModule
           ]

Creating a list

We will create an exportable data object in a new file we will call data.ts ``and then use an Angular service to expose the data to any component that imports it.

Create a new file in the app folder called data.ts and then populate it with artists like thus:

    // src/app/data.ts

    export const artists = [
    {
    number: "1",
    name: "Davido"
    },
    {
    number: "2",
    name: "Wizkid"
    },
    {
    number: "3",
    name: "Burna Boy"
    },
    {
    number: "4",
    name: "Patoranking"
    },
    {
    number: "5",
    name: "Maleek Berry"
    },
    {
    number: "6",
    name: "Mr. Eazi",
    },
    {
    number: "7",
    name: "Mayorkun"
    },
    {
    number: "8",
    name: "Peruzzi"
    },
    {
    number: "9",
    name: "Teni"
    },
    {
    number: "10",
    name: "Olamide"
    },
    {
    number: "11",
    name: "Phyno"
    },
    {
    number: "12",
    name: "M.I"
    },
    {
    number: "13",
    name: "Ycee"
    },
    {
    number: '14",
    name: "Dremo"
    },
    {
    number: "15",
    name: "Zlatan"
    },
    {
    number: "16",
    name: "Reminnisce"
    },
    {
    number: "17",
    name: "Tiwa Savage"
    },
    {
    number: "18",
    name: "Seyi Shay"
    },
    {
    number: "19",
    name: "Blaqbonez"
    },
    {
    number: "20",
    name: "Tekno"
    },
    {
    number: "21",
    name: "Niniola"
    }
    ]

Create a service called artists with this command in your project terminal:

    ng g service artists

This generates a service called artists in your app component. You can add the flag to remove the test spec file like this:

    ng g service --skipTests artists 

You should see a new file in the app folder called artists.service.ts ``and it should look like this:

    // src/app/artists.service.ts

    import { Injectable } from@angular/core’;
    import { artists } from './data'
    @Injectable({
    providedIn: ‘root’
    })
    export class ArtistsService {
     constructor() { }
    }

To bring in the data to be used by the artists service, we return artists (as specified in the export statement in the data) in the constructor like so:

    // src/app/artists.service.ts

    export class ArtistsService {
     constructor() { }
      getArtists(){
       return artists;
       }
     }

Now we have to create a component for the artists where we can populate the hard coded data we have. Run the command below:

    ng g component -skipTests artists

This creates a component called artists and we can then pull the data on the artists service to the artists component using the lifecycle method when the component initializes like this:

    // src/app/artists/artists.component.ts 
    import { Component, OnInit } from '@angular/core';
    import { ArtistsService } from '../artists.service';
    @Component({
      selector: 'app-artists',
      templateUrl: './artists.component.html',
      styleUrls: ['./artists.component.css']
    })
    export class ArtistsComponent implements OnInit {
     constructor(private artistsService: ArtistsService) { }
      artists = [];
      ngOnInit() {
       this.getArtists();
      }
      getArtists (){
       this.artists = this.artistsService.getArtists();
       }
     }

Clear everything currently in the app.component.html and just replace with this selector instead:

    <app-artists></app-artists>

Creating items

Now that we have brought in the data through the artists service, let’s deal with the presentation and styling. To implement virtual scrolling in the user interface, Angular provides an HTML-like tag that tells Angular that the content inside the tag will have virtual scrolling implemented.

That is the <cdk-virtual-scroll-viewport> tag and when you want to use the virtual scrolling feature, Angular provides a special ngFor for you to use instead of the regular one. It is called *cdkVirtualFor and it does exactly the same thing as ngFor only that ngFor can not be used inside the virtual scroll tag.

It is compulsory to set the itemSize property on the viewport, as it will return an error if omitted.

*cdkVirtualFor has a few variables you can use for logic on your template:

  • index : the index of the item in the data source.
  • count : the total number of items in the data source.
  • first : whether this is the first item in the data source.
  • last : whether this is the last item in the data source.
  • even: whether the index is even.
  • odd: whether the index is odd.

It is important to note that all these variables apply to the item index in the data source not in the rendered data. Normally, to display the artists, we have to use ngFor syntax like this:

    // src/app/artists/artists.component.html
    <div class="container">
      <h2>Brits Performing artists</h2>
      <div class="example-viewport">
        <div *ngFor="let artist of artists" class="list">
          <h2>{{artist.name}}</h2>
        </div>
      </div>
    </div>

Now, we use the virtual scroll syntax like this:

    // src/app/artists/artists.component.ts 
    <div class="container">
      <h2>Brits Performing artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
     <div *cdkVirtualFor="let artist of artists" class="list">
       <h2>{{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>

We can then style the viewport and the list items like this:

    // src/app/artists/artists.component.css

    .example-viewport{
     height: 250px;
     width: 25%;
     margin-left: 50px;
     border: 1px solid saddlebrown;
     display: flex;
    }
    .list{
     height: 50px;
     justify-content: center;
     align-items: center;
    }
    h2{
     margin-left: 40px;
    }
    .container{
     margin-bottom: 40px;
    }

You can now run your application in development environment with the command

    ng serve

Open your browser at http://localhost:4200/ and you should see your application like this:

If you take a look at the developer tools and inspect the elements section, you will notice that list items are added and removed from the DOM dynamically as you scroll. That is the awesome power of the virtual scrolling feature that shipped with the Component Development Kit.

Demo: a simple use case

If you have followed the article to this point, you must have by now started to have some ideas of how to implement the virtual scrolling feature in your next project. One of these use cases can be to create a hall of fame list featuring performers from the annual BRITs awards.

What we will be building

Coding the hall of fame

The few modifications made to achieve this demo above were done in the following component files: Add the following to the artists.component.html file:

    // src/app/artists/artists.component.html

    <h1>Brits Performance Hall of Fame</h1>
    <div class="container">
      <h2>2019 Artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
      <div *cdkVirtualFor="let artist of artists" class="list">
        <h2>{{artist.number}}. {{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>
    <div class="container">
      <h2>2018 Artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
      <div *cdkVirtualFor="let artist of artists" class="list">
        <h2>{{artist.number}}. {{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>
    <div class="container">
      <h2>2017 Artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
      <div *cdkVirtualFor="let artist of artists" class="list">
        <h2>{{artist.number}}. {{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>

Add the following to the artists.component.css file

    // src/app/artists/artists.component.css

    .example-viewport{
      height: 250px;
      width: 25%;
      margin-left: 50px;
      border: 1px solid saddlebrown;
      display: flex;
    }
    .list{
      height: 80px;
      justify-content: center;
      align-items: center;
    }
    h2{
      margin-left: 40px;
    }
    h1{
      margin-left: 18px;
    }
    .container{
      margin-bottom: 40px;
      display: flex;
    }

Add the following to the artists.components.ts file

    import { Component, OnInit } from '@angular/core';
    import { ArtistsService } from '../artists.service';
    @Component({
    selector: 'app-artists',
    templateUrl: './artists.component.html',
    styleUrls: ['./artists.component.css']
    })
    export class ArtistsComponent implements OnInit {
     constructor(private artistsService: ArtistsService) { }
      artists = [];
      ngOnInit() {
      this.getArtists();
    }
    getArtists (){
      this.artists = this.artistsService.getArtists();
      }
     }

Your application should now be up to date with our demo, you can now run it in the development environment

    ng serve

Conclusion

The Component Development Kit provides a lot of features that helps developers enhance the development process of the user interface. This tutorial gives you a quick guide to the syntax and usage of the virtual scrolling feature. You can find the official documentation here. You can download the code in this tutorial from here. Documentation for other Angular Material CDK features can be found here.

Check out my blog post about the drag and drop tool. Happy Coding!

Clone the project repository
  • Angular
  • TypeScript
  • no pusher tech

Products

  • Channels
  • Beams
  • Chatkit

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.