How to build virtual scroll lists with rxVirtualFor
Goal. Practical recipes for @rx-angular/template/virtual-scrolling: basic setup,
persisting rendered views (appendOnly), trackBy, custom and window scroll elements,
reverse infinite scroll, and extending the package. For the full API, see the
RxVirtualFor,
viewport, and
strategy references.
Setup
Three parts must be imported and glued together:
- the viewport:
RxVirtualScrollViewportComponent - the view repeater:
RxVirtualFor - a scroll strategy: e.g.
FixedSizeVirtualScrollStrategy
import {
FixedSizeVirtualScrollStrategy, // choose any strategy you like
RxVirtualScrollViewportComponent,
RxVirtualFor,
} from '@rx-angular/template/virtual-scrolling';
@Component({
imports: [RxVirtualFor, RxVirtualScrollViewportComponent, FixedSizeVirtualScrollStrategy],
})
export class MyComponent {}
Render a fixed-size list
The rxVirtualForOf input accepts an Observable, a Signal, or a static array.
Size the items in CSS to match the strategy's itemSize.
<rx-virtual-scroll-viewport [itemSize]="50">
<div class="hero" *rxVirtualFor="let hero of heroes$">
<strong>{{ hero.name }}</strong>
<div>{{ hero.description }}</div>
</div>
</rx-virtual-scroll-viewport>
.hero {
height: 50px; // items must be sized to match itemSize
}
@Component({
/* … */
})
export class AnyComponent {
heroes$: Observable<Hero[]> = getHeroes();
// a Signal or a plain array works too:
heroesSignal: Signal<Hero[]> = getHeroesSignal();
}
Keep rendered views with appendOnly
appendOnly keeps views in the DOM after they scroll out of view instead of recycling
them. Useful when integrating with @angular/cdk/drag-drop. It reacts to changes, so
it can be toggled at runtime.
<rx-virtual-scroll-viewport [itemSize]="50" appendOnly>
<div class="hero" *rxVirtualFor="let hero of heroes; trackBy: 'id'">
<strong>{{ hero.name }}</strong>
</div>
</rx-virtual-scroll-viewport>
Reduce boilerplate with trackBy
trackBy accepts either a keyof T shorthand or a regular
TrackByFunction ((index: number, item: T) => any).
<rx-virtual-scroll-viewport [itemSize]="50">
<div class="hero" *rxVirtualFor="let hero of heroes; trackBy: 'id'">
<strong>{{ hero.name }}</strong>
</div>
</rx-virtual-scroll-viewport>
Use a custom scroll element
Apply rxVirtualScrollElement to an outer element to make it the scroll container, so
you can place content before and after the viewport.
<div rxVirtualScrollElement>
<div>Any content you like before</div>
<rx-virtual-scroll-viewport [itemSize]="50">
<div *rxVirtualFor="let item of items$">{{ item }}</div>
</rx-virtual-scroll-viewport>
<div>Any content you like after</div>
</div>
The bundled strategies detect when they are fully hidden from the viewport (accounting
for the size of content before and after) and render the minimum of runwayItems /
runwayItemsOpposite.
Scroll with the window
Add the scrollWindow directive to use the browser window as the scroll element,
especially useful for mobile.
<rx-virtual-scroll-viewport [itemSize]="50" scrollWindow>
<div *rxVirtualFor="let item of items$">{{ item }}</div>
</rx-virtual-scroll-viewport>
Reverse infinite scroll (keepScrolledIndexOnPrepend)
A reversed infinite scroller starts at the bottom and prepends data when the user
hits the top (as in a chat window). Set keepScrolledIndexOnPrepend so the strategy
keeps the visible content in place as new data arrives. The item at the bottom edge
of the viewport is the one kept in place, so a transient "loading older messages" row
at the top can be inserted and removed without moving what the user reads.
import { Component, inject } from '@angular/core';
import { Subject } from 'rxjs';
import { AutoSizeVirtualScrollStrategy, ListRange, RxVirtualFor, RxVirtualScrollViewportComponent } from '@rx-angular/template/virtual-scrolling';
@Component({
imports: [RxVirtualScrollViewportComponent, RxVirtualFor, AutoSizeVirtualScrollStrategy],
})
export class ReverseInfiniteListComponent {
private dataService = inject(MessageService);
initialScrollIndex = 19;
listRange: ListRange = { start: 0, end: 0 };
scrolled$ = new Subject<number>();
viewsRendered$ = new Subject<Message[]>();
messages$ = this.scrolled$.pipe(
filter(() => this.listRange.start === 0), // only fetch at the start
startWith(0),
exhaustMap((_, index) => this.dataService.getMessages(index)),
scan((messages, newMessages) => [...newMessages, ...messages], []),
);
trackMessage = (index: number, message: Message) => message.id;
}
<rx-virtual-scroll-viewport autosize keepScrolledIndexOnPrepend [initialScrollIndex]="initialScrollIndex" (viewRange)="listRange = $event" (scrolledIndexChange)="scrolled$.next($event)">
<div
*rxVirtualFor="
let item of messages$;
trackBy: trackMessage;
renderCallback: viewsRendered$
"
>
<div>{{ item.message.text }}</div>
<div>{{ item.sendAt | date }}</div>
</div>
</rx-virtual-scroll-viewport>
Hide the viewport with display: none
Some routers and page stacks keep a page in the DOM and hide it with display: none
instead of destroying it — Ionic's navigation stack and cached router outlets do this.
The viewport tolerates that: an element inside a display: none subtree has no layout
box at all, and measurements taken in that state are ignored instead of being booked as
a real size. The cached item sizes, the rendered range and the scroll position therefore
survive the hide/show cycle. Nothing needs to be configured.
Note that this is about elements that are not rendered, not about elements that measure
zero. An item that is rendered but happens to be 0px tall — an empty item template, or
one collapsed via height: 0 — is still measured and booked as usual. The one case that
cannot be told apart from a hidden page is putting display: none on the item's own root
element: such an item keeps its previously measured size until it is shown again. Prefer
filtering those items out of the data source, or collapse them with height: 0.
Extend the package with a custom strategy
Because every part of the package is based on injection tokens, you can provide your own
RxVirtualScrollStrategy. Create a directive that provides itself as the strategy token
and extends the abstract base, implementing scrolledIndex$, renderedRange$,
contentSize$, attach(), detach(), and scrollToIndex(). attach() is called when
the strategy connects to a viewport (wire up your scroll listeners there) and detach()
when it disconnects (tear them down there).
See Extending with a custom strategy
for a worked example and a pointer to the simplest shipped implementation,
FixedSizeVirtualScrollStrategy, to read as a full reference.
Result
You have a viewport that renders only the visible slice of a large iterable, scheduled
without blocking the UI thread. Use the viewRange and scrolledIndexChange outputs to
react to what is on screen.
See also
- Reference:
RxVirtualFor - Reference:
RxVirtualScrollViewport - Reference: Virtual scroll strategies
- How-to: Tune rendering with strategies
- Concept: Concurrent scheduling & the frame budget