Angular Virtual Scrolling - ngVirtualScrolling

Yes!. Angular 7 is out with some cool new features. I really appreciate that you wanted to experience the brand new Angular. Here in this post, I am going to explain a bit about one of the Angular 7 feature, which is Virtual Scrolling. At the end of this article, you will have an application which fetches the real data from the database and binds it to the UI by using Virtual Scrolling feature. I am not sure about you, but I am super excited to develop a sample application with this feature. Enough talking, let’s jump into the setup. I hope you will find this post useful.

Yes! Angular 7 is out with some cool new features. I really appreciate that you wanted to experience the brand new Angular. Here, in this post, I am going to explain a bit about one of the Angular 7 features, Virtual Scrolling. At the end of this article, you will have an application that fetches the real data from the database and binds it to the UI by using the Virtual Scrolling feature. I am not sure about you, but I am super excited to develop a sample application with this feature. Enough talking, let’s jump into the setup. I hope you will find this post useful. You can always see this article in my blog here.

As Angular 7 came out last week, I wanted to try a few things with it, and that is the reason for this article. If you are really new to Angular and want to try some other things, please check the Angular articles on my blog.

Creating ngVirtualScrolling app

The first thing we are going to do is to create a dummy application.

Installing Angular CLI

Yes, as you guessed, we are using Angular CLI. If you haven’t installed Angular CLI, I recommend you to install the same. It is a great CLI tool for Angular, I am sure you will love that. You can do that by running the below command.

npm install -g @angular/cli

Once we set up this project we will be using the Angular CLI commands and you can check the official Angular cli documentation for understanding the things you can do with the CLI.

Generating a new project

Now it is time to generate our new project. We can use the below command for this.

ng new ngVirtualScrolling

And you will be able to see all the hard work this CLI is doing for us.

Generate ng project

Now that we have created our application, let’s run our application and see if it is working or not.

Build and open in the browser

As we develop we will be using the Angular material for the design and we can install it now itself along with the animation and cdk.

install material, cdk, and animation

With the Angular 6+ versions you can also do this by following the below command.

ng add @angular/material

Generating components

Now our project is ready and we can start creating the components. Again, CLI is going to do the work for us for free. If it were a freelance developer, how much would you pay him/her?

ng g c home

ng g c header

ng g c footer

Now we have three components to work with. So let’s begin.

Set up header component

I am going to edit only the HTML of the header component for myself and not going to add any logic. You can add anything you wish.

Every Angular app will be having at least one NgModule class, and AppModule resides in a file named app.module.ts. You can always learn about the Angular architecture in the official Angular documentation.

Do you see a ScrollingModule there? You should import it to use the virtual scrolling and it resides in the @angular/cdk/scrolling. As you might have already noticed, we have added one service called MovieService in the provider's array. We will create one now.

Creating a movie service

import {

Injectable

} from '@angular/core';

import {

RequestMethod,

RequestOptions,

Request,

Http

} from '@angular/http';

import {

config

} from './config';

@Injectable({

providedIn: 'root'

})

exportclass MovieService {

constructor(private http: Http) {}

get(url: string) {

returnthis.request(url, RequestMethod.Get)

}

request(url: string, method: RequestMethod): any {

const requestOptions = new RequestOptions({

method: method,

url: `${config.api.baseUrl}${url}${config.api.apiKey}`

});

const request = new Request(requestOptions);

returnthis.http.request(request);

}

}

As you can see I haven’t done much with the service class and didn’t implement the error mechanism and other things as I wanted to make this as short as possible. This service will fetch the movies from an online database TMDB and here in this article and repository, I am using mine. I strongly recommend you to create your own instead of using mine. Can we set up the config file now?

Set up config.ts

A configuration file is a way to arrange things handily and you must implement in all the projects you are working with.

const config = {

api: {

baseUrl: 'https://api.themoviedb.org/3/movie/',

apiKey: '&api_key=c412c072676d278f83c9198a32613b0d',

topRated: 'top_rated?language=en-US&page=1'

}

}

export {

config

};

Creating a movie component

Let’s create a new component now to load the movie into it. Basically, we will be using this movie component inside the cdkVirtualFor so that it will call this component each time and render it. Out movie component will be having the HTML as below.

Here itemSize is a mandatory property and you can give any number as per how much data you want to load to the component. We are inputting the values to our app-movie component by using [movie]=”movie”.

Let’s see the typescript code now.

import {

Component,

OnInit,

ChangeDetectionStrategy

} from '@angular/core';

import {

DataSource,

CollectionViewer

} from '@angular/cdk/collections';

import {

BehaviorSubject,

Subscription,

Observable

} from 'rxjs';

import {

MovieService

} from '../movie.service';

import {

Movie

} from '../models/movie';

import {

config

} from '../config';

@Component({

selector: 'app-home',

templateUrl: './home.component.html',

styleUrls: ['./home.component.scss'],

changeDetection: ChangeDetectionStrategy.OnPush

})

exportclass HomeComponent {

constructor(private movieService: MovieService) {}

ds = new MyDataSource(this.movieService);

}

exportclass MyDataSource extends DataSource < Movie | undefined > {

private page = 1;

private initialData: Movie[] = [{

id: 19404,

title: 'Dilwale Dulhania Le Jayenge',

overview: 'Raj is a rich, carefree, happy-go-lucky second generation NRI. Simran is the daughter of Chaudhary Baldev Singh, who in spite of being an NRI is very strict about adherence to Indian values. Simran has left for India to be married to her childhood fiancé. Raj leaves for India with a mission at his hands, to claim his lady love under the noses of her whole family. Thus begins a saga.',

I have a parent HomeComponent where I get the data from a class, MyDataSource, which extends DataSource<Movie | undefined>. This DataSource is an abstract class and residing in @angular/cdk/collections. As the MyDataSource class is extending from DataSource, we had to override two functions which are, connect() and disconnect(). According to the Angular material documentation, the connect method will be called by the virtual scroll viewport to receive a stream that emits the data array that should be rendered. The viewport will call disconnect when the viewport is destroyed, which may be the right time to clean up any subscriptions that were registered during the connect process.

Inside the connect method, we are calling our own service to get the data.

this.movieService.get(config.api.topRated).subscribe((data) => {

this.formatDta(JSON.parse(data._body).results);

});

Custom styling

I have applied some custom styles to some components, which you can see in the GitHub repository. Please copy those from there if you are creating the application from scratch.

Output

Once you have implemented all the steps, you will have an application which uses Angular 7 virtual scrolling with actual server data. Now, let us run the application and see it in action.

Angular Virtual Scrolling Demo Start

Angular Virtual Scrolling Demo Middle

Conclusion

In this post, we have learned how to:

Create an Angular 7 application

Work with Angular CLI

Generate components in Angular

Use Material design

Work with virtual scrolling in Angular 7

Please feel free to play with this GitHub repository. It may not be a perfect article on this topic, so please do share with me your findings while you work on the same. I really appreciate that, thanks in advance.

Your turn. What do you think?

Thanks a lot for reading. I will come back with another post on the same topic very soon. Did I miss anything that you may think is needed? Did you find this post useful? Please share with me your valuable suggestions and feedback, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on Stack Overflow instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.