Angular7 - Materials/CDK-Virtual Scrolling



This is one of the new features added to Angular 7 called as Virtual Scrolling. This feature is added to CDK (Component Development Kit). Virtual scrolling shows up the visible dom elements to the user, as the user scrolls, the next list is displayed. This gives faster experience as the full list is not loaded at one go and only loaded as per the visibility on the screen.

Why do we need Virtual Scrolling Module?

Consider you have a UI which has a big list where loading all the data together can have performance issues. The new feature of Angular 7 Virtual Scrolling takes care of loading the elements which are visible to the user. As the user scrolls, the next list of dom elements visible to user is displayed. This gives faster experience and the scrolling is also very smooth.

Let us add the dependency to our project −

npm install @angular/cdk –save
Virutal Scrolling Module

We are done with installing the dependency for virtual scrolling module.

We will work on an example to get a better understanding on how we can use virtual scrolling module in our project.

We will first add the virtual scrolling module inside app.module.ts as follows −

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
import { MyserviceService } from './myservice.service';
import { HttpClientModule } from '@angular/common/http';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';

@NgModule({
   declarations: [
      SqrtPipe,
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective,
      RoutingComponent
   ],
   imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule,
      ScrollDispatchModule
   ],
   providers: [MyserviceService],
   bootstrap: [AppComponent]
})
export class AppModule { }

In app.module.ts, we have imported the ScrollDispatchModule and the same is added to imports array as shown in the code above.

Next step is to get data to be displayed on the screen. We will continue to use the service we created in the last chapter.

We will fetch data from the url, https://jsonplaceholder.typicode.com/photos which has data for around 5000 images. We will get the data from it and display to the user using virtual scrolling module.

The details in the url, https://jsonplaceholder.typicode.com/photos are as follows −

Jsonplaceholder

It is json data that has image url and thumbnail url. We will show the thumbnail url to the users.

Following is the service which will fetch data −

myservice.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
   providedIn: 'root'
})
export class MyserviceService {
   private finaldata = [];
   private apiurl = "https://jsonplaceholder.typicode.com/photos";
   constructor(private http: HttpClient) { }
   getData() {
      return this.http.get(this.apiurl);
   }
}

We will call the service from app.component.ts as follows −

import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 7 Project!';
   public albumdetails = [];
   constructor(private myservice: MyserviceService) {}
   ngOnInit() {
      this.myservice.getData().subscribe((data) => {
         this.albumdetails = Array.from(Object.keys(data), k=>data[k]);
         console.log(this.albumdetails);
      });
   }
}

Now the variable albumdetails has all the data from the api and the total count is 5000.

Now that we have the data ready to be displayed, let us work inside app.component.html to display the data.

We need to add the tag, <cdk-virtual-scroll-viewport></cdk-virtual-scroll-viewport> to work with virtual scroll module. The tag needs to be added to .html file where we want the data to be displayed.

Here is the working of <cdk-virtual-scroll-viewport> in app.component.html.

<h3>Angular 7 - Virtual Scrolling</h3>
<cdk-virtual-scroll-viewport [itemSize] = "20">
   <table>
      <thead>
         <tr>
            <td>ID</td>
            <td>ThumbNail</td>
         </tr>
      </thead>
      <tbody>
         <tr *cdkVirtualFor = "let album of albumdetails">
            <td>{{album.id}}</td>
            <td>
               <img src = "{{album.thumbnailUrl}}" width = "100" height = "100"/>
            </td>
         </tr>
      </tbody>
   </table>
</cdk-virtual-scroll-viewport>

We are displaying the id and thumbnail url to the user on the screen. We have mostly used *ngFor so far, but inside <cdk-virtual-scroll-viewport>, we have to use *cdkVirtualFor to loop through the data.

We are looping through albumdetails variable which is populated inside app.component.html. There is a size assigned to the virtual tag [itemSize]="20" which will display the number of items based on the height of the virtual scroll module.

The css related to the virtual scroll module is as follows −

table {
   width: 100%;
}
cdk-virtual-scroll-viewport {
   height: 500px;
}

The height given to the virtual scroll is 500px. The images that fit within that height will be displayed to the user. We are done with adding the necessary code to get our virtual scroll module to be viewed.

The output of Virtual Scroll Module in the browser is as follows −

Virtual Scrolling

We can see the first 4 images are displayed to the user. We have specified the height of 500px. There is scroll displayed for the table, as the user scrolls, the images which will fit in that height will be displayed as shown below −

User Scrolls

The required images are loaded as the user scrolls. This feature is very useful in terms of performance. At first go, it does not load all the 5000 images, instead as the user scrolls, the urls are called and displayed.

Advertisements