@angular/cdk/scrolling package provides utilities for virtual scrolling and detecting scroll events.
Installation
Virtual Scrolling
Basic Virtual Scroll
Render large lists efficiently by only rendering visible items:Fixed Size Items
Variable Size Items
For items with different heights, useautosize:
Horizontal Scrolling
Advanced Virtual Scrolling
Track By Function
Template Context
Scroll to Index
Scroll Events
Scroll Detection
CdkScrollable Directive
ScrollDispatcher
Listen to scroll events globally:ViewportRuler
Get viewport dimensions:API Reference
CdkVirtualScrollViewport
Selector:cdk-virtual-scroll-viewport
| Input | Type | Description |
|---|---|---|
itemSize | number | Size of each item in pixels |
minBufferPx | number | Minimum buffer size |
maxBufferPx | number | Maximum buffer size |
orientation | 'vertical' | 'horizontal' | Scroll orientation |
appendOnly | boolean | Only append new items |
| Output | Type | Description |
|---|---|---|
scrolledIndexChange | number | Emits first visible index |
| Method | Returns | Description |
|---|---|---|
scrollToIndex(index, behavior?) | void | Scroll to index |
scrollToOffset(offset, behavior?) | void | Scroll to pixel offset |
scrollTo(options) | void | Scroll with options |
measureScrollOffset(from?) | number | Get current scroll offset |
elementScrolled() | Observable<Event> | Scroll event observable |
getRenderedRange() | ListRange | Get visible range |
getDataLength() | number | Get total item count |
cdkVirtualFor Directive
Selector:[cdkVirtualFor]
Similar to *ngFor but for virtual scrolling.
CdkScrollable Directive
Selector:[cdkScrollable]
Marks an element as scrollable for the ScrollDispatcher.
Performance Tips
- Use trackBy - Essential for performance
- Fixed item sizes - Faster than autosize
- Buffer size - Adjust
minBufferPxandmaxBufferPx - OnPush change detection - Use for list items
- Avoid complex templates - Keep item templates simple