Angular 7 Tutorial: Create Angular Material CDK Virtual Scroll

by Didin J. on Oct 26, 2018 Angular 7 Tutorial: Create Angular Material CDK Virtual Scroll

A comprehensive step by step tutorial on creating Angular 7 Material CDK virtual scroll with remote data example

A comprehensive step by step tutorial on creating Angular 7 Material CDK virtual scroll with remote data example. Previously, we have introduced the Angular 7 CRUD web application. Now, we learn deeply one of the new features that introduce when Angular 7 released. It's an Angular 7 virtual scroll with remote data example.

Jumps to the steps:

Angular Material is a Material Design for Angular application that implementing Google's Material Design specification. Material Design uses more grid-based layouts, responsive animations and transitions, padding, and depth effects such as lighting and shadows. CDK is an abbreviation for Component Development Kit which is a set of tools that implement common interaction patterns whilst being unopinionated about their presentation.

The data that get remotely in this example is 5000 items but render to the list just a few items, so it keeps view size smaller.

The following tools, frameworks, and modules are required for this tutorial:

  1. Node.js (recommended version)
  2. Angular 7 CLI
  3. Angular 7
  4. Terminal (Mac/Linux) or Node Command Line (Windows)
  5. IDE or Text Editor

We assume that you have installed Node.js. Now, we need to check the Node.js and NPM versions. Open the terminal or Node command line then type this commands.

node -v
v8.12.0
npm -v
6.4.1

That's the Node.js and NPM version that we are using. Now, you can go to the main steps.


Install or Update Angular 7 CLI and Create Application

To install or update Angular 7 CLI, type this command in the Terminal or Node Command Line.

sudo npm install -g @angular/cli

Now, you have the latest version of Angular CLI.

ng --version

Angular CLI: 7.0.2
Node: 8.12.0
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.10.2
@angular-devkit/core         7.0.2
@angular-devkit/schematics   7.0.2
@schematics/angular          7.0.2
@schematics/update           0.10.2
rxjs                         6.3.3
typescript                   3.1.3

Next, create a new Angular 7 Web Application using this Angular CLI command.

ng new angular7-virtual-scroll

If you get the question like below, choose `No` and `SCSS` (or whatever you like to choose).

? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? SCSS

Next, go to the newly created Angular 7 project folder.

cd angular7-virtual-scroll

Type this command to run the Angular 7 application using this command.

ng serve

Open your browser then go to this address `localhost:4200`, you should see this Angular 7 page.


Create Service for Accessing REST API

Before show a service for REST API access, first, we have to install or register `HttpClientModule`. Open and edit `src/app/app.module.ts` then add this import.

import { HttpClientModule } from '@angular/common/http';

Add it to `@NgModule` imports after `BrowserModule`.

imports: [
  BrowserModule,
  BrowserAnimationsModule,
  HttpClientModule
],

To create an Angular 7 service, simply run this command.

ng g service api

Next, open and edit `src/api.service.ts` then add these imports of RxJS Observable, of, throwError, Angular HttpClient, HttpHeaders, HttpErrorResponse, RxJS Operators catchError, tap, map, and Photos object model.

import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Photos } from './photos';

Add these constants before the `@Injectable`.

const apiUrl = "https://jsonplaceholder.typicode.com/photos";

Inject `HttpClient` module to the constructor.

constructor(private http: HttpClient) { }

Add the error handler function.

private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}

Add the function for getting or load all data from the RESTful API.

getPhotos (): Observable<Photos[]> {
  return this.http.get<Photos[]>(apiUrl)
    .pipe(
      tap(todos => console.log('Fetch todos')),
      catchError(this.handleError('getPhotos', []))
    );
}

Create this file `src/app/photos.ts` for the type handling of the API response.

touch src/app/photos.ts

Open and edit that file then add these lines of Typescript code.

export class Photos {
  albumId: number;
  id: number;
  title: string;
  url: string;
  thumbnailUrl: string;
}


Install and Configure Angular Material and CDK

This is the main feature of this Angular 7 tutorial, to install Angular 7 Material and CDK type this command.

ng add @angular/material

Next, register all required Angular Material components or modules to `app.module.ts`. Open and edit that file then add this imports.

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

Register the above modules to `@NgModule` imports.

imports: [
  BrowserModule,
  BrowserAnimationsModule,
  ScrollingModule,
  MatCardModule,
  HttpClientModule
],


Create an Angular CDK Virtual Scroll

We will implement the Angular 7 CDK Virtual Scroll inside the existing `src/app/app.component.html`. For that, open and edit that file then replace all HTML tags with this.

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<div class="container">
  <mat-card>
    <cdk-virtual-scroll-viewport itemSize="50" class="example-viewport">
      <div *cdkVirtualFor="let item of ds" class="example-item">
        <div class="img-item">
          <img src="{{item.thumbnailUrl}}" alt="{{item.title}}" />
        </div>
        <div class="p-item">
          <p>{{item.title}}</p>
        </div>
      </div>
    </cdk-virtual-scroll-viewport>
  </mat-card>
</div>

Next, open and edit `src/app/app.component.ts` then add/replace these imports.

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { ApiService } from './api.service';
import { Photos } from './photos';

Add this parameter to Angular 7 `@Component`.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})

Add these variables and constructor inside `AppComponent` class.

title = 'Angular 7 CDK Virtual Scroll';
ds = new MyDataSource(this.api);

constructor(private api: ApiService) {}

Create a new class below the `AppComponent` class with these lines of codes.

export class MyDataSource extends DataSource<Photos> {

  private photos:Photos[];
  private dataStream = new BehaviorSubject<Photos[]>([]);

  constructor(private api: ApiService) {
    super();
  }

  connect() {
    this.api.getPhotos()
      .subscribe((photos) => {
        this.photos = photos;
        this.dataStream.next(this.photos);
      });

    return this.dataStream;
  }

  disconnect(): void {
  }

}

Now, we will give this page a little style. Open and edit `src/app/app.component.scss` then add this lines of SASS codes.

.container {
  width: 96%;
  margin: 10px auto;
  .example-viewport {
    height: 220px;
    width: 100%;
    border: 1px solid black;
    background: white;
    border: solid 1px #999;
  }
  .example-item {
    height: 160px;
    padding: 5px 10px;
    color: #999;
    .img-item {
        float: left;
        width: 25%;
    }
    .p-item {
        float: left;
        width: 75%;
    }
  }
}


Run and Test the Angular 7 Material and CDK Application

To test the Angular 7 application, simply type this command to run it first.

ng serve

Open the browser and point to `http://localhost:4200` and you will see this page.

Angular 7 Tutorial: Create Angular Material CDK Virtual Scroll - CDK Virtual Scroll

You can check how Angular 7 CDK Virtual Scroll works by open your browser HTML inspector and you should see the item in the list rendered alternately.

That it's, the Angular 7 Tutorial: Create Angular Material CDK Virtual Scroll. You can check the working source code from our GitHub.

If you don’t want to waste your time design your own front-end or your budget to spend by hiring a web designer then Angular Templates is the best place to go. So, speed up your front-end web development with premium Angular templates. Choose your template for your front-end project here.

That just the basic. If you need more deep learning about MEAN Stack, Angular, and Node.js, you can take the following cheap course:

Thanks!

Loading…