Full answer
Infinite scroll appends content as the user nears the end of a list. A scroll listener that measures positions on every scroll event is wasteful. The IntersectionObserver API tells you when an element enters the viewport, with no layout reads in your code.
Design:
- A directive
[appInView]on a sentinel element (an emptydivafter the list). It owns the observer. - Create the observer in
afterNextRender, becauseIntersectionObserverand layout do not exist on the server.rootMargin: '200px'fires a little before the sentinel is visible, so loading starts before the user hits the end. - When
isIntersectingis true, the directive emitsinView. - The component handles the output: if
loading()ordone(), return. Otherwise setloading, fetch the next page, append with[...old, ...next], and clearloading. DestroyRef.onDestroy(() => observer.disconnect())cleans up.
Edge cases:
- After new items are appended the sentinel moves down and leaves the viewport, so the observer fires again when it re-enters. If the first page is short and the sentinel stays visible, the observer will not fire again, because intersection did not change. Handle it by loading until the list fills the viewport, or by unobserving and observing again after each load.
- Errors: show a retry button and do not loop.
- End of data: hide the sentinel and show "No more results".
- Accessibility: infinite scroll can trap keyboard users away from the footer. Offer a "Load more" button as an alternative, and announce new items with a polite live region.
- Memory: for thousands of rows combine with virtual scroll or pagination.
A "Load more" button is the simplest accessible version, and many products use it instead of automatic loading.
typescript
import { Component, DestroyRef, Directive, ElementRef, afterNextRender, inject, input, output, signal } from '@angular/core';
@Directive({ selector: '[appInView]' })
export class InViewDirective {
readonly rootMargin = input('200px');
readonly inView = output<void>();
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly destroyRef = inject(DestroyRef);
constructor() {
afterNextRender(() => {
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
this.inView.emit();
}
},
{ rootMargin: this.rootMargin() },
);
observer.observe(this.host.nativeElement);
this.destroyRef.onDestroy(() => observer.disconnect());
});
}
}
@Component({
selector: 'app-feed',
imports: [InViewDirective],
template: `
<ul>
@for (item of items(); track item) {
<li>{{ item }}</li>
}
</ul>
@if (done()) {
<p>No more results</p>
} @else {
<div appInView (inView)="loadMore()" aria-hidden="true"></div>
<button type="button" [disabled]="loading()" (click)="loadMore()">
{{ loading() ? 'Loading...' : 'Load more' }}
</button>
}
<p aria-live="polite">{{ items().length }} items loaded</p>
`,
})
export class FeedComponent {
readonly items = signal<string[]>([]);
readonly loading = signal(false);
readonly done = signal(false);
constructor() {
this.loadMore();
}
loadMore(): void {
if (this.loading() || this.done()) {
return;
}
this.loading.set(true);
setTimeout(() => {
const start = this.items().length;
const next = Array.from({ length: 20 }, (_, i) => `Post ${start + i + 1}`);
this.items.update((old) => [...old, ...next]);
this.done.set(this.items().length >= 60);
this.loading.set(false);
}, 200);
}
}Angular 20.3, strict template check passes. The fake API returns 20 items per page up to 60.
Key points
- `IntersectionObserver` on a sentinel replaces scroll listeners.
- Create it in `afterNextRender` for SSR safety and disconnect on destroy.
- Guard against duplicate loads with `loading` and `done` flags.
- Provide a "Load more" button for accessibility and keyboard users.
Common mistakes
- Creating the observer in the constructor and crashing during server rendering.
- Not guarding against repeated loads while a request is running.
- Forgetting that the observer does not fire again if the sentinel stays visible after loading.
Follow-ups
- How would you re-trigger loading if the first page does not fill the screen?
- How do you test code that depends on IntersectionObserver?
- Why use `rootMargin`?
Tips
- Say why not a scroll listener (layout reads on every event).
- Mention the "sentinel stays visible" bug. It shows you have shipped one of these.
- Offer the button alternative for accessibility.
Evaluation rubric
- Creates and cleans up the observer safely.
- Implements load guards and end-of-data states.
- Considers accessibility and edge cases.