How to use Virtual Scrolling using Angular 7 CDK
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:
- 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)
- 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.
- 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.
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
- 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
Live example: https://angular-yni1jw.stackblitz.io
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. 🚀