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 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.

Source Code

The source code can be found 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.

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

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.

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?


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.

  1. <div style="text-align:center">  
  2.     <h1> Welcome to ngVirtualScrolling at <a href="">Sibeesh Passion</a>  
  3.     </h1>  
  4. </div>  
Set up footer component
  1. <p> Copyright @SibeeshPassion 2018 - 2019 :) </p>  
Set up app-routing.module.ts

We are going to create a route only for home.

  1. import {  
  2.     NgModule  
  3. } from '@angular/core';  
  4. import {  
  5.     Routes,  
  6.     RouterModule  
  7. } from '@angular/router';  
  8. import {  
  9.     HomeComponent  
  10. } from './home/home.component';  
  11. const routes: Routes = [{  
  12.     path: '',  
  13.     redirectTo: '/home',  
  14.     pathMatch: 'full'  
  15. }, {  
  16.     path: 'home',  
  17.     component: HomeComponent  
  18. }];  
  19. @NgModule({  
  20.     imports: [RouterModule.forRoot(routes)],  
  21.     exports: [RouterModule]  
  22. })  
  23. export class AppRoutingModule {}  
Set up router outlet in app.component.html

Now we have a route and it is time to set up the outlet.

  1. <app-header></app-header>  
  2. <router-outlet>  
  3. </router-outlet>  
  4. <app-footer></app-footer>  
Set up app.module.ts

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.

  1. import {  
  2.     BrowserModule  
  3. } from '@angular/platform-browser';  
  4. import {  
  5.     NgModule  
  6. } from '@angular/core';  
  7. import {  
  8.     MatButtonModule,  
  9.     MatCheckboxModule,  
  10.     MatMenuModule,  
  11.     MatCardModule,  
  12.     MatSelectModule  
  13. } from '@angular/material';  
  14. import {  
  15.     AppRoutingModule  
  16. } from './app-routing.module';  
  17. import {  
  18.     AppComponent  
  19. } from './app.component';  
  20. import {  
  21.     HeaderComponent  
  22. } from './header/header.component';  
  23. import {  
  24.     FooterComponent  
  25. } from './footer/footer.component';  
  26. import {  
  27.     HomeComponent  
  28. } from './home/home.component';  
  29. import {  
  30.     ScrollingModule  
  31. } from '@angular/cdk/scrolling';  
  32. import {  
  33.     MovieComponent  
  34. } from './movie/movie.component';  
  35. import {  
  36.     MovieService  
  37. } from './movie.service';  
  38. import {  
  39.     HttpModule  
  40. } from '@angular/http';  
  41. import {  
  42.     BrowserAnimationsModule  
  43. } from '@angular/platform-browser/animations';  
  44. @NgModule({  
  45.     declarations: [  
  46.         AppComponent,  
  47.         HeaderComponent,  
  48.         FooterComponent,  
  49.         HomeComponent,  
  50.         MovieComponent  
  51.     ],  
  52.     imports: [  
  53.         HttpModule,  
  54.         BrowserModule,  
  55.         AppRoutingModule,  
  56.         ScrollingModule,  
  57.         MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule  
  58.     ],  
  59.     exports: [  
  60.         HttpModule,  
  61.         BrowserModule,  
  62.         AppRoutingModule,  
  63.         ScrollingModule,  
  64.         MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule  
  65.     ],  
  66.     providers: [MovieService],  
  67.     bootstrap: [AppComponent]  
  68. })  
  69. export class AppModule {}  

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
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     RequestMethod,  
  6.     RequestOptions,  
  7.     Request,  
  8.     Http  
  9. } from '@angular/http';  
  10. import {  
  11.     config  
  12. } from './config';  
  13. @Injectable({  
  14.     providedIn: 'root'  
  15. })  
  16. export class MovieService {  
  17.     constructor(private http: Http) {}  
  18.     get(url: string) {  
  19.         return this.request(url, RequestMethod.Get)  
  20.     }  
  21.     request(url: string, method: RequestMethod): any {  
  22.         const requestOptions = new RequestOptions({  
  23.             method: method,  
  24.             url: `${config.api.baseUrl}${url}${config.api.apiKey}`  
  25.         });  
  26.         const request = new Request(requestOptions);  
  27.         return this.http.request(request);  
  28.     }  
  29. }  

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.

  1. const config = {  
  2.     api: {  
  3.         baseUrl: '',  
  4.         apiKey: '&api_key=c412c072676d278f83c9198a32613b0d',  
  5.         topRated: 'top_rated?language=en-US&page=1'  
  6.     }  
  7. }  
  8. export {  
  9.     config  
  10. };  
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.

  1. <div class="container">  
  2.     <mat-card style="min-height: 500px;" class="example-card">  
  3.         <mat-card-header>  
  4.             <div mat-card-avatar class="example-header-image"></div>  
  5.             <mat-card-title>{{movie?.title}}</mat-card-title>  
  6.             <mat-card-subtitle>Release date: {{movie?.release_date}}</mat-card-subtitle>  
  7.         </mat-card-header>  
  8.         <img mat-card-image src="{{movie?.poster_path}}" alt="{{movie?.title}}">  
  9.         <mat-card-content>  
  10.             <p>  
  11.                 {{movie?.overview}}  
  12.             </p>  
  13.         </mat-card-content>  
  14.     </mat-card>  
  15. </div>  

And the typescript file will be having one property with @Input decorator so that we can input the values to it from the home component.

  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     Input  
  5. } from '@angular/core';  
  6. import {  
  7.     Movie  
  8. } from '../models/movie';  
  9. @Component({  
  10.     selector: 'app-movie',  
  11.     templateUrl: './movie.component.html',  
  12.     styleUrls: ['./movie.component.scss']  
  13. })  
  14. export class MovieComponent implements OnInit {  
  15.     @Input()  
  16.     movie: Movie;  
  17.     constructor() {}  
  18.     ngOnInit() {}  
  19. }  
Set up home component

Now here is the main part, the place where the virtual scrolling is happening. Let’s design the HTML now.

  1. <div class="container" style="text-align:center">  
  2.     <div class="row">  
  3.         <cdk-virtual-scroll-viewport itemSize="500" class="example-viewport">  
  4.             <app-movie *cdkVirtualFor="let movie of ds" [movie]="movie" class="example-item">{{movie || 'Loading...'}}</app-movie>  
  5.         </cdk-virtual-scroll-viewport>  
  6.     </div>  
  7. </div>  

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.

  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     ChangeDetectionStrategy  
  5. } from '@angular/core';  
  6. import {  
  7.     DataSource,  
  8.     CollectionViewer  
  9. } from '@angular/cdk/collections';  
  10. import {  
  11.     BehaviorSubject,  
  12.     Subscription,  
  13.     Observable  
  14. } from 'rxjs';  
  15. import {  
  16.     MovieService  
  17. } from '../movie.service';  
  18. import {  
  19.     Movie  
  20. } from '../models/movie';  
  21. import {  
  22.     config  
  23. } from '../config';  
  24. @Component({  
  25.     selector: 'app-home',  
  26.     templateUrl: './home.component.html',  
  27.     styleUrls: ['./home.component.scss'],  
  28.     changeDetection: ChangeDetectionStrategy.OnPush  
  29. })  
  30. export class HomeComponent {  
  31.     constructor(private movieService: MovieService) {}  
  32.     ds = new MyDataSource(this.movieService);  
  33. }  
  34. export class MyDataSource extends DataSource < Movie | undefined > {  
  35.     private page = 1;  
  36.     private initialData: Movie[] = [{  
  37.         id: 19404,  
  38.         title: 'Dilwale Dulhania Le Jayenge',  
  39.         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.',  
  40.         poster_path: '\/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'  
  41.     }];  
  42.     private dataStream = new BehaviorSubject < (Movie | undefined)[] > (this.initialData)  
  43.     private subscription = new Subscription();  
  44.     constructor(private movieService: MovieService) {  
  45.         super();  
  46.     }  
  47.     connect(collectionViewer: CollectionViewer): Observable < (Movie | undefined)[] > {  
  48.         this.subscription.add(collectionViewer.viewChange.subscribe((range) => {  
  49.             console.log(range.start)  
  50.             console.log(range.end)  
  51.             this.movieService.get(config.api.topRated).subscribe((data) => {  
  52.                 this.formatDta(JSON.parse(data._body).results);  
  53.             });  
  54.         }));  
  55.         return this.dataStream;  
  56.     }  
  57.     disconnect(): void {  
  58.         this.subscription.unsubscribe();  
  59.     }  
  60.     formatDta(_body: Movie[]): void {  
  62.     }  
  63. }  

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.

  1. this.movieService.get(config.api.topRated).subscribe((data) => {  
  2.     this.formatDta(JSON.parse(data._body).results);  
  3. });  
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.


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.


In this post, we have learned how to:

  1. Create an Angular 7 application
  2. Work with Angular CLI
  3. Generate components in Angular
  4. Use Material design
  5. 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.