As a developer, you’ve probably had to implement a big list or table for your application using an infinite scroll technique.

The problem with that is that so many elements in the DOM can cause slow initial rendering, laggy scrolling, and dirty checking on each one of them in the context of Angular can be expensive.

Virtual Scroll

The central concept behind virtual rendering is rendering only the visible items.

For example, if there are thousands of alerts in an application, an efficient way would be to load only the elements that are visible and unload them when they are not by replacing them with new ones.

An initial implementation of virtual scrolling is now available in @angular/cdk. (v7.0.0-beta.0)

Let’s see two examples of how to use them.

First, we need to install the cdk package and import the ScrollingModule module.

yarn add @angular/cdk@7.0.0-beta.0

Next, let’s create a component that renders a list.

We create an array of 10000 items, and each cell contains the number 30. Let’s move forward to the template.

Demo

The autosize attribute indicates we want to use a virtual scroll strategy that supports unknown or dynamic size items. The rest of the code is self-explanatory.

Live Demo

Note: An autosize strategy that works on elements of differing sizes is currently being developed in @angular/cdk-experimental , but it is not ready for production use yet.

The next example is using fixed item size and observable.

Fixed Size & Observale

Continue playing in stackblitz.

Live demo from StackBlitz. Try editing the code yourself.

You can find full examples here. For further information check out the docs.

Follow me on Medium or Twitter to read more about Angular, Vue and JS!

Things to not miss: