Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

Angular
Home›Angular›Angular Virtual Scrolling – ngVirtualScrolling

Angular Virtual Scrolling – ngVirtualScrolling

By SibeeshVenu
October 24, 2018
501
0
Share:
Angular Virtual Scrolling Demo Middle

[toc]

Introduction

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

Source Code

The source code can be found here.

Background

As Angular 7 is out last week, I wanted to try a few things with the same and that is the cause for this article. If you are really new to Angular, and if you need to try some other things, visiting my articles on the same topic wouldn’t be a bad idea.

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 see here 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 the same.

ng new ngVirtualScrolling

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

Generate ng project

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 browser

Build and open in 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

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 is a freelance developer, how much would you pay him/her?

ng c home

ng g c home

ng g c header

ng g c header

ng g c footer

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.

<div style="text-align:center">
  <h1>
    Welcome to ngVirtualScrolling at <a href="https://sibeeshpassion.com">Sibeesh Passion</a>
  </h1>
</div>

Set up footer component

<p>
  Copyright @SibeeshPassion 2018 - 2019 :)
</p>

Set up app-routing.module.ts

We are going to create a route only for home.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
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.

<app-header></app-header>
<router-outlet>
</router-outlet>
<app-footer></app-footer>

Set up app.module.ts

Every Angular app will be having at least one NgModule class, the same is named as andAppModule resides in a file named app.module.ts. You can always learn about the Angular architecture here.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule} from '@angular/material';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './home/home.component';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { MovieComponent } from './movie/movie.component';
import { MovieService } from './movie.service';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    HomeComponent,
    MovieComponent
  ],
  imports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    ScrollingModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule
  ],
  exports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    ScrollingModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule
  ],
  providers: [ MovieService ],
  bootstrap: [AppComponent]
})
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 providers 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'
})
export class MovieService {
  constructor(private http: Http) {
  }

  get(url: string) {
    return this.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);
    return this.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 in handy 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.

<div class="container">
  <mat-card style="min-height: 500px;" class="example-card">
    <mat-card-header>
      <div mat-card-avatar class="example-header-image"></div>
      <mat-card-title>{{movie?.title}}</mat-card-title>
      <mat-card-subtitle>Release date: {{movie?.release_date}}</mat-card-subtitle>
    </mat-card-header>
    <img mat-card-image src="https://image.tmdb.org/t/p/w370_and_h556_bestv2/{{movie?.poster_path}}" alt="{{movie?.title}}">
    <mat-card-content>
      <p>
        {{movie?.overview}}
      </p>
    </mat-card-content>
  </mat-card>
</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.

import { Component, OnInit, Input } from '@angular/core';
import { Movie } from '../models/movie';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.scss']
})
export class MovieComponent implements OnInit {
  @Input()
  movie: Movie;
  
  constructor() { 
  }

  ngOnInit() {
  }

}

Set up home component

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

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

Here itemSize is a mandatory property and you can give any number as per how many 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
})

export class HomeComponent {
  constructor(private movieService: MovieService) {
  }
  ds = new MyDataSource(this.movieService);
}

export class 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.',
      poster_path: '\/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
    }
  ];
  private dataStream = new BehaviorSubject<(Movie | undefined)[]>(this.initialData)
  private subscription = new Subscription();

  constructor(private movieService: MovieService) {
    super();
  }

  connect(collectionViewer: CollectionViewer): Observable<(Movie | undefined)[]> {
    this.subscription.add(collectionViewer.viewChange.subscribe((range) => {
      console.log(range.start)
      console.log(range.end)
      this.movieService.get(config.api.topRated)
        .subscribe((data) => {
          this.formatDta(JSON.parse(data._body).results);
        });
    }));
    return this.dataStream;
  }

  disconnect(): void {
    this.subscription.unsubscribe();
  }

  formatDta(_body: Movie[]): void {
    this.dataStream.next(_body);
  }
}

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

Output

Once you have implemented all the steps, you will be having 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 Start

Angular Virtual Scrolling Demo Middle

Angular Virtual Scrolling Demo Middle

 

Conclusion

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 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 which is needed? Could you find this post as useful? Please share 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.

Kindest Regards
Sibeesh Venu

TagsAngularAngular 7cdk-virtual-scroll-viewportDeferred ScrollingngngVirtualScrollingScrollingModuleVirtual Scrolling
Previous Article

npm vs npx

Next Article

Iterating/Loop Through Your Component Property in Render ...

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • locaStorage in Protractor
    Angular

    End to End (E2E) Tests in Angular Application Using Protractor

    July 8, 2018
    By SibeeshVenu
  • Angular_App_Folder_Structure
    Angular

    Angular 5 Basic Demo Project Overview

    November 15, 2017
    By SibeeshVenu
  • Nav_Demo
    Angular

    Generating Your First Components And Modules in Angular 5 App

    November 16, 2017
    By SibeeshVenu
  • ngDragDrop After Adding
    Angular

    New Angular Drag and Drop Feature – ngDragDrop

    October 30, 2018
    By SibeeshVenu
  • AngularHow to

    Validation Using Template Driven Forms in Angular 5

    April 22, 2018
    By SibeeshVenu
  • AngularAzureCognitive Services

    Using Azure Cognitive Service Computer Vision AI to read text from an image

    April 4, 2019
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version