Blog>
Snippets

Virtual Scrolling with Angular CDK

Provide a code snippet on how to use Angular CDK's virtual scrolling to efficiently render large lists by only displaying elements in the DOM that are currently in view.
import { ScrollingModule } from '@angular/cdk/scrolling';
Import ScrollingModule from @angular/cdk/scrolling in the module where you want to use the virtual scroll feature.
@NgModule({
  imports: [
    ScrollingModule,
    // ... other modules you may need ...
  ]
  // ... other NgModule metadata ...
})
export class YourModule { }
Include ScrollingModule in the imports array of your Angular Module.
<cdk-virtual-scroll-viewport itemSize="50" class="example-viewport">
  <div *cdkVirtualFor="let item of items" class="example-item">
    {{item.name}}
  </div>
</cdk-virtual-scroll-viewport>
Use the cdk-virtual-scroll-viewport directive in your component template. The itemSize property sets the height of the items in pixels. Items will be rendered inside the viewport using the *cdkVirtualFor directive.
import { Component } from '@angular/core';

@Component({
  selector: 'app-virtual-scroll-list',
  templateUrl: './virtual-scroll-list.component.html',
  styleUrls: ['./virtual-scroll-list.component.css']
})
export class VirtualScrollListComponent {
  items = [];

  constructor() {
    for (let i = 0; i < 10000; i++) { this.items.push({name: `Item #${i}`}); }
  }
}
In your component class, define the items array that will be rendered in the virtual scroll. Here, we're populating 10,000 items for the sake of example.
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';

export class VirtualScrollListComponent {
  // ...

  constructor(private viewPort: CdkVirtualScrollViewport) {}

  scrollToIndex(index: number): void {
    this.viewPort.scrollToIndex(index);
  }
}
To programmatically scroll to a particular index, inject CdkVirtualScrollViewport in your component's constructor and use the scrollToIndex method.