How to Add Virtual Scrolling Using Angular

Posted By : Damandeep Singh | 31-Oct-2018

Virtual scrolling is the latest feature in Angular 7. It helps to maintain the performance issue of Website. Virtual is scrolling is provided by Angular CDK or  Angular Material.

 

We use virtual scrolling where heavy chunks of data will be shown with scrolling, because the heavy chunks of data can lead to performance issues.

 

Virtual Scrolling loads and unloads elements from the DOM based on the visible parts of a list, making it possible to build fast experiences for users with very large scrollable lists.

Import the package into an app.module file 

import {ScrollDispatchModule} from '@angular/cdk/scrolling';

The <cdk-virtual-scroll-viewport> displays large lists of elements performantly by only rendering the items that fit on the screen. Loading hundreds of elements can easily create a performance issue in any browser. Virtual Scrolling enables a performant way to simulate all items being rendered by making the height of the container elements as the height of a total number of elements to be rendered in the view. Virtual Scrolling is different from strategies like infinite scroll and else. where it renders a set amount of list and then when you hit the end renders the rest.

 

cdkVirtualFor replaces *ngFor inside a <cdk-virtual-scroll-viewport>
supporting the exact same API as *ngFor.
for eg.

<cdk-virtual-scroll-viewpoert itemSize="50" class="viewport">
 <div *cdkVirtualFor=" let list for items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>

The Virtual Scrolling will remove the un-visible part from the DOM and stores only visible part which will help to maintain performance.

View Orientation

The Default orientation of virtual scroll viewport is vertical, but it can also be changed to horizontal using orientation attribute. while changing the orientation ensure that items to be aligned with CSS.

<cdk-virtual-scroll-viewport orientation="horizontal" itemSize="50" class="example-viewport">
    <div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
  </cdk-virtual-scroll-viewport>

according to the sample example, you can target to the example-item class to change the writing mode accordingly.

So basically,

  • Virtual Scrolling can easily show 'n' number of data in a block easily and helps to maintain perfomance with heavy data.
  • DOM will store only the data, which is visible in viewport and remove the other data while scrolling. whether we use Static data or Dynamic Data.  

About Author

Author Image
Damandeep Singh

Damandeep Singh is a Front-end Developer having Good knowledge of HTML, CSS3/CSS, Bootstrap, Angular, Ionic. He likes to listen to Music in Free time.

Request for Proposal

Name is required

Comment is required

Sending message..