How to use Virtual Scrolling using Angular 7 CDK

Zain Zafar
Frontend Weekly
Published in
2 min readOct 21, 2018

Sometimes developers have to display thousands of elements at a time in a table or list. Adding these many number of items in the DOM can cause problems and forces the application to slow down.

But fortunately there is a technique called Virtual Scroll to display the items without slowing the app down.

Let’s evaluate all the options before getting into Virtual Scroll.

There are 3 ways to handle this:

  1. Pagination: Paginate your list and show items as chunks it’s performant but you can’t get the whole snapshot of your list at once and you also have to click back and forth between pages. (e.g. Google Search Results)
  2. Infinite Scroll: Initially loads only few items and keep appending more items to the list as you scroll, it gives the complete snapshot of the list but as more and more items keep adding, list is going to slow down eventually as the number of nodes in the DOM are increasing and thus application will start slowing down.
  3. Virtual Scroll: Display only small subset of the data that is in the viewport and keep changing the records as the user scrolls. It keep the number of DOM elements constant hence boosting the performance of the application.

NOTE: Virtual Scroll is simply a strategy that can be used inside a list or even infinite scroll. It has nothing to do it with the way you implement it, it can be plain list or infinite scroll or for that matter any other strategy that you may prefer.

List of 10K items rendered using Virtual with Angular’s ScrollModule

Demo: https://angular-yni1jw.stackblitz.io

Installation

Make sure you are running Angular 7 application

Type the following command to add Angular CDK version 7.0

NPM

npm install @angular/cdk@7.0.0

Angular CLI

ng add @angular/cdk@7.0.0

Setup

  1. Import Scrolling Module into your application app.module.ts

2. Generate 10000 items list in your app.component.ts

3. Let’s render the list in app.component.html file

Styling

[OPTIONAL] — add styles to the application in your styles.css file

Preview

Virtual Scroll in action

StackBlitz Code: https://stackblitz.com/edit/angular-yni1jw

GitHub Repo: https://github.com/zainzafar90/virtual-scroll-angular-cdk

For further information check out the docs.

Thanks for reading. 🚀

--

--

Zain Zafar
Frontend Weekly

Frontend Enthusiast, JavaScript Hacker with affinity to Design & Blogger