Virtual scroll strategies
A RxVirtualScrollStrategy positions the views created by *rxVirtualFor inside the
viewport. All three pre-packaged strategies position
views absolutely and move them with CSS transforms, and share a common set of inputs.
Exactly one strategy must be applied, via its attribute selector, to the
<rx-virtual-scroll-viewport> element.
Why this matters: see How RxAngular virtual scrolling works and Concurrent scheduling & the frame budget.
Import
import { FixedSizeVirtualScrollStrategy, DynamicSizeVirtualScrollStrategy, AutoSizeVirtualScrollStrategy, RxVirtualScrollStrategy } from '@rx-angular/template/virtual-scrolling';
Shared inputs
Every pre-packaged strategy exposes these inputs.
| Input | Type | Default | Description |
|---|---|---|---|
runwayItems | number | 10 | Number of items rendered upfront in scroll direction. |
runwayItemsOpposite | number | 2 | Number of items rendered upfront in the opposite scroll direction. |
appendOnly | boolean | false | Keep already-rendered views in the DOM after they scroll out of view. Reacts to changes; can be toggled at runtime. This widens the viewRange output, use visibleRange to observe what is actually visible. |
keepScrolledIndexOnPrepend | boolean | false | Keep the visible content in place when data changes before it, e.g. prepends. The item at the bottom edge of the viewport stays put. Used for reverse infinite scrollers. |
FixedSizeVirtualScrollStrategy
Positions views based on a single fixed item size. Comparable to the CDK
FixedSizeVirtualScrollStrategy, but with the high-performance layout technique.
- Selector:
rx-virtual-scroll-viewport[itemSize] - Class:
FixedSizeVirtualScrollStrategy<T, U>
| Input | Type | Default | Description |
|---|---|---|---|
itemSize | number | 50 | Fixed size (in px) of every item, set via [itemSize]. |
import { Component } from '@angular/core';
import { FixedSizeVirtualScrollStrategy, RxVirtualScrollViewportComponent, RxVirtualFor } from '@rx-angular/template/virtual-scrolling';
@Component({
imports: [RxVirtualFor, FixedSizeVirtualScrollStrategy, RxVirtualScrollViewportComponent],
template: `
<rx-virtual-scroll-viewport [itemSize]="itemSize">
<div class="item" *rxVirtualFor="let item of items$">{{ item.content }}</div>
</rx-virtual-scroll-viewport>
`,
})
export class MyComponent {
itemSize = 50;
items$ = inject(DataService).getItems();
}
DynamicSizeVirtualScrollStrategy
Calculates each item's size from a user-provided function instead of reading the DOM, so it has better runtime performance than the autosize strategy when the sizes are known ahead of time.
- Selector:
rx-virtual-scroll-viewport[dynamic] - Class:
DynamicSizeVirtualScrollStrategy<T, U>
| Input | Type | Default | Description |
|---|---|---|---|
dynamic | (item: T) => number | — | Function returning the size (in px) of a given item, bound via [dynamic]. |
@Component({
imports: [RxVirtualFor, DynamicSizeVirtualScrollStrategy, RxVirtualScrollViewportComponent],
template: `
<rx-virtual-scroll-viewport [dynamic]="dynamicSize">
<div class="item" *rxVirtualFor="let item of items$">
{{ item.content }}
@if (item.description) {
<div>{{ item.description }}</div>
}
</div>
</rx-virtual-scroll-viewport>
`,
})
export class MyComponent {
// items with a description are 120px tall, others 50px
dynamicSize = (item: Item) => (item.description ? 120 : 50);
items$ = inject(DataService).getItems();
}
Forcing a recalculation
The strategy runs the dynamic function for every item whenever the data changes.
If the size of your items also depends on state outside of the data - a toggled
detail section, the width of the viewport, the current locale - bind a new function
reference to [dynamic]. The strategy detects the changed reference, re-runs the
function for the whole dataset and re-positions the list. The item at the top of the
viewport stays where it is, the scroll position follows the new size of the content
above it.
@Component({
imports: [RxVirtualFor, DynamicSizeVirtualScrollStrategy, RxVirtualScrollViewportComponent],
template: `
<button (click)="showTimestamps.set(!showTimestamps())">toggle timestamps</button>
<rx-virtual-scroll-viewport [dynamic]="dynamicSize()">
<div class="item" *rxVirtualFor="let item of items$">
@if (showTimestamps()) {
<div>{{ item.timestamp }}</div>
}
{{ item.content }}
</div>
</rx-virtual-scroll-viewport>
`,
})
export class MyComponent {
readonly showTimestamps = signal(false);
// a new function reference is created whenever `showTimestamps` changes
readonly dynamicSize = computed(() => {
const withTimestamps = this.showTimestamps();
return (item: Item) => (withTimestamps ? 70 : 50);
});
items$ = inject(DataService).getItems();
}
Recalculating is an O(n) operation over the whole dataset, so only swap the
function reference when the outcome of the calculation actually changed.
AutoSizeVirtualScrollStrategy
Renders and positions items based on their individual measured size, using a
ResizeObserver to react to size changes. Comparable to the CDK experimental
autosize strategy, but with better visual stability and a working scrollToIndex /
scrolledIndexChange.
- Selector:
rx-virtual-scroll-viewport[autosize] - Class:
AutoSizeVirtualScrollStrategy<T, U>
| Input | Type | Default | Description |
|---|---|---|---|
tombstoneSize | number | 50 | Anticipated size for not-yet-measured views, used to size the runway. |
withResizeObserver | boolean | true | Observe rendered views for size changes and re-position accordingly. |
withSyncScrollbar | boolean | false | Keep the scrollbar synchronized during measurement. |
resizeObserverConfig | { options?: ResizeObserverOptions; extractSize?: (entry: ResizeObserverEntry) => number; } | — | Configuration forwarded to the internal ResizeObserver. |
@Component({
imports: [RxVirtualFor, AutoSizeVirtualScrollStrategy, RxVirtualScrollViewportComponent],
template: `
<rx-virtual-scroll-viewport autosize>
<div class="item" *rxVirtualFor="let item of items$">{{ item.content }}</div>
</rx-virtual-scroll-viewport>
`,
})
export class MyComponent {
items$ = inject(DataService).getItems();
}
Extending with a custom strategy
All parts of the package are based on injection tokens. To provide a custom strategy,
create a directive that provides itself as RxVirtualScrollStrategy and extends it
(the abstract base already implements some helpers, e.g. getElement() and the
viewRenderCallback subject used by *rxVirtualFor).
RxVirtualScrollStrategy requires you to implement three observables and three
methods:
| Member | Description |
|---|---|
scrolledIndex$: Observable<number> | Emits the index of the first item currently visible in the viewport. |
renderedRange$: Observable<ListRange> | Emits the { start, end } slice of the iterable that should currently be rendered to the DOM. |
contentSize$: Observable<number> | Emits the total scrollable size (in px) of the list, used to size the viewport's scrollbar. |
attach(viewport, viewRepeater) | Called when the strategy is connected to a viewport. Wire up your scroll listeners and start computing ranges here. |
detach() | Called when the strategy is disconnected (e.g. on ngOnDestroy). Tear down subscriptions here. |
scrollToIndex(index, behavior?) | Scroll the viewport so the item at index becomes visible. |
A minimal fixed-size implementation looks like this:
import { Directive } from '@angular/core';
import { ReplaySubject } from 'rxjs';
import { distinctUntilChanged, map, startWith, takeUntil } from 'rxjs/operators';
import { ListRange, RxVirtualScrollStrategy, RxVirtualScrollViewport, RxVirtualViewRepeater } from '@rx-angular/template/virtual-scrolling';
const ITEM_SIZE = 50;
@Directive({
selector: 'rx-virtual-scroll-viewport[custom]',
providers: [{ provide: RxVirtualScrollStrategy, useExisting: CustomScrollStrategy }],
})
export class CustomScrollStrategy extends RxVirtualScrollStrategy<any> {
private viewport: RxVirtualScrollViewport | null = null;
private readonly detached$ = new ReplaySubject<void>(1);
private readonly _scrolledIndex$ = new ReplaySubject<number>(1);
readonly scrolledIndex$ = this._scrolledIndex$.pipe(distinctUntilChanged());
private readonly _renderedRange$ = new ReplaySubject<ListRange>(1);
readonly renderedRange$ = this._renderedRange$.asObservable();
private readonly _contentSize$ = new ReplaySubject<number>(1);
readonly contentSize$ = this._contentSize$.asObservable();
attach(viewport: RxVirtualScrollViewport, viewRepeater: RxVirtualViewRepeater<any>): void {
this.viewport = viewport;
viewRepeater.values$
.pipe(
map((values) => (Array.isArray(values) ? values.length : 0)),
takeUntil(this.detached$),
)
.subscribe((length) => this._contentSize$.next(length * ITEM_SIZE));
// compute the range initially and on every scroll event
viewport.elementScrolled$.pipe(startWith(undefined), takeUntil(this.detached$)).subscribe(() => {
const start = Math.floor(viewport.getScrollTop() / ITEM_SIZE);
this._scrolledIndex$.next(start);
this._renderedRange$.next({ start, end: start + 20 }); // + a fixed runway
});
// every rendered view is positioned absolutely inside the viewport
viewRepeater.viewRendered$.pipe(takeUntil(this.detached$)).subscribe(({ view, item }) => {
const index = view.context.index;
this.getElement(view).style.transform = `translateY(${index * ITEM_SIZE}px)`;
this.viewRenderCallback.next({ view, item, index });
});
}
detach(): void {
this.detached$.next();
this.viewport = null;
}
scrollToIndex(index: number, behavior?: ScrollBehavior): void {
this.viewport?.scrollTo(index * ITEM_SIZE, behavior);
}
}
Two parts make the list visible: the range has to be emitted before the first scroll
event (startWith), and every rendered view has to be positioned, because all views
are position: absolute inside the viewport. Emitting viewRenderCallback keeps the
renderCallback of *rxVirtualFor working.
The example leaves out direction aware runway/overscan handling, coalescing scroll
events and support for an offset between the scroll container and the viewport. For a
complete, production-ready reference, read the source of the simplest shipped strategy:
FixedSizeVirtualScrollStrategy.
See also
- Reference:
RxVirtualFor - Reference:
RxVirtualScrollViewport - How-to: Virtual scroll recipes
- Explanation: How RxAngular virtual scrolling works
- Concept: Concurrent scheduling & the frame budget