# Angular Infinite Scroll Directive

InfiniteScroll loads the next page of a list when its end comes into view, down or up, with a load more fallback for keyboard users. It has no dependency and is built on IntersectionObserver.

## Basic

Add pInfiniteScroll to a list that scrolls and load the next page on scrolled . The event is emitted when the end of the list comes within distance of the bottom of the container, 200 pixels by default, and again after the new items are rendered if the end is still in view, so a first page that does not fill the container keeps asking. Bind loading so that nothing is asked while a page is on its way, and set hasMore to false once the last page has arrived. itemSelector tells the directive which elements are the items, here the articles and not the loading message.

```typescript
import { Component, signal } from '@angular/core';
import { InfiniteScroll, InfiniteScrollEvent } from '@exhaustive-ui/core/infinitescroll';
import { spinner } from '@exhaustive-ui/icons/round';
import { SvgIcon } from '@exhaustive-ui/core/icon';

interface Article {
    id: number;
    title: string;
}

@Component({
    template: `
        <div class="card">
            <div pInfiniteScroll itemSelector="article" [loading]="loading()" [hasMore]="hasMore()" (scrolled)="load($event)" role="feed" aria-label="Articles" class="h-80 overflow-auto border border-surface rounded-border">
                @for (article of articles(); track article.id) {
                    <article
                        tabindex="0"
                        [attr.aria-labelledby]="'basic-article-' + article.id"
                        [attr.aria-posinset]="article.id"
                        [attr.aria-setsize]="hasMore() ? -1 : articles().length"
                        class="px-4 py-3 border-b border-surface focus-visible:outline-2 focus-visible:outline-primary"
                    >
                        <span [id]="'basic-article-' + article.id" class="font-medium">{{ article.title }}</span>
                        <p class="m-0 text-sm text-muted-color">Article {{ article.id }} of 100</p>
                    </article>
                }
                @if (loading()) {
                    <div class="flex items-center justify-center gap-2 p-4 text-muted-color"><svg pIcon [icon]="spinner" spin aria-hidden="true"></svg> Loading...</div>
                }
                @if (!hasMore()) {
                    <div class="p-4 text-center text-muted-color">You have seen all the articles.</div>
                }
            </div>
        </div>
    `,
    standalone: true,
    imports: [SvgIcon, InfiniteScroll]
})
export class InfinitescrollBasicDemo {
    spinner = spinner;

    articles = signal<Article[]>([]);

    loading = signal(false);

    hasMore = signal(true);

    load(event: InfiniteScrollEvent) {
        this.loading.set(true);
        // a request to the server, simulated with a timer
        setTimeout(() => {
            const page = Array.from({ length: 10 }, (_, i) => event.itemCount + i + 1).map((id) => ({ id, title: `Article ${id}` }));
            this.articles.update((articles) => [...articles, ...page]);
            this.hasMore.set(this.articles().length < 100);
            this.loading.set(false);
        }, 600);
    }
}
```

## Window Scroll

When the page itself scrolls, add scrollWindow : the end of the list is then measured against the viewport. Without it, the directive uses the host when it scrolls, otherwise its nearest scrolling ancestor, otherwise the page. scrollContainer names another container, as an element or a CSS selector. Scroll this page down past the grid: it stops after 48 photos.

```typescript
import { Component, signal } from '@angular/core';
import { InfiniteScroll } from '@exhaustive-ui/core/infinitescroll';

interface Photo {
    id: number;
    title: string;
}

@Component({
    template: `
        <div class="card">
            <div pInfiniteScroll scrollWindow [distance]="100" itemSelector="figure" [loading]="loading()" [hasMore]="photos().length < 48" (scrolled)="load()" class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                @for (photo of photos(); track photo.id) {
                    <figure class="m-0 flex flex-col gap-2">
                        <div class="h-24 rounded-border bg-emphasis flex items-center justify-center text-2xl font-semibold" aria-hidden="true">{{ photo.id }}</div>
                        <figcaption class="text-sm">{{ photo.title }}</figcaption>
                    </figure>
                }
            </div>
            @if (loading()) {
                <p class="text-center text-muted-color mt-4 mb-0">Loading more photos...</p>
            }
        </div>
    `,
    standalone: true,
    imports: [InfiniteScroll]
})
export class InfinitescrollWindowscrollDemo {
    photos = signal<Photo[]>([]);

    loading = signal(false);

    load() {
        this.loading.set(true);
        setTimeout(() => {
            const start = this.photos().length;
            this.photos.update((photos) => [...photos, ...Array.from({ length: 8 }, (_, i) => ({ id: start + i + 1, title: `Photo ${start + i + 1}` }))]);
            this.loading.set(false);
        }, 500);
    }
}
```

## Reverse

With direction="up" , the list starts at its end and scrolledUp asks for older items when its start comes into view, like the history of a chat. The directive keeps the visible messages in place while older ones are inserted above them, so the reader does not lose their position, and keeps the list at its end when a new message arrives while the reader is already there. scrollToEnd() brings the newest message into view, after sending one for example.

```typescript
import { Component, signal, viewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { InfiniteScroll } from '@exhaustive-ui/core/infinitescroll';
import { InputTextModule } from '@exhaustive-ui/core/inputtext';

interface Message {
    id: number;
    author: string;
    text: string;
    mine: boolean;
}

@Component({
    template: `
        <div class="card">
            <div class="flex flex-col gap-3 max-w-xl mx-auto">
                <div
                    pInfiniteScroll
                    #history="pInfiniteScroll"
                    direction="up"
                    itemSelector="[data-message]"
                    [loading]="loading()"
                    [hasMore]="hasMore()"
                    (scrolledUp)="loadOlder()"
                    role="region"
                    aria-label="Conversation"
                    tabindex="0"
                    class="h-80 overflow-auto border border-surface rounded-border p-3 flex flex-col gap-2"
                >
                    @if (!hasMore()) {
                        <p class="text-center text-sm text-muted-color m-0">Start of the conversation</p>
                    }
                    @if (loading()) {
                        <p class="text-center text-sm text-muted-color m-0">Loading older messages...</p>
                    }
                    @for (message of messages(); track message.id) {
                        <div data-message class="max-w-[80%] px-3 py-2 rounded-border" [class]="message.mine ? 'self-end bg-primary text-primary-contrast' : 'self-start bg-emphasis'">
                            <span class="block text-xs font-semibold">{{ message.author }}</span>
                            {{ message.text }}
                        </div>
                    }
                </div>
                <form class="flex gap-2" (ngSubmit)="send()">
                    <input pInputText name="draft" [(ngModel)]="draft" aria-label="Message" placeholder="Write a message" class="flex-1" />
                    <p-button type="submit" label="Send" [disabled]="!draft.trim()" />
                </form>
            </div>
        </div>
    `,
    standalone: true,
    imports: [InfiniteScroll, FormsModule, ButtonModule, InputTextModule]
})
export class InfinitescrollReverseDemo {
    history = viewChild.required<InfiniteScroll>('history');

    messages = signal<Message[]>(this.page(1000, 15));

    loading = signal(false);

    hasMore = signal(true);

    draft = '';

    loadOlder() {
        this.loading.set(true);
        setTimeout(() => {
            const oldest = this.messages()[0].id;
            this.messages.update((messages) => [...this.page(oldest - 15, 15), ...messages]);
            this.hasMore.set(oldest - 15 > 925);
            this.loading.set(false);
        }, 600);
    }

    send() {
        const text = this.draft.trim();
        if (text) {
            const last = this.messages()[this.messages().length - 1].id;
            this.messages.update((messages) => [...messages, { id: last + 1, author: 'You', text, mine: true }]);
            this.draft = '';
            setTimeout(() => this.history().scrollToEnd());
        }
    }

    page(start: number, size: number): Message[] {
        return Array.from({ length: size }, (_, i) => {
            const id = start + i;
            const mine = id % 3 === 0;
            return { id, author: mine ? 'You' : 'Amy', text: `Message ${id - 924}`, mine };
        });
    }
}
```

## DataView and Table

Components that render all their rows, like DataView, Listbox or a Table without virtual scrolling, work the same way: put the directive on an element around them that scrolls, or name their own scroll container with scrollContainer , and append the new page to their value. Leave their paginator out. Below, a DataView in a scrolling container, then a scrollable Table whose body scrolls inside .p-datatable-table-container , made focusable through pt so that it scrolls with the keyboard.

```typescript
import { Component, signal } from '@angular/core';
import { DataViewModule } from '@exhaustive-ui/core/dataview';
import { InfiniteScroll } from '@exhaustive-ui/core/infinitescroll';
import { TableModule } from '@exhaustive-ui/core/table';
import { TagModule } from '@exhaustive-ui/core/tag';

interface Item {
    id: number;
    name: string;
    category: string;
    price: number;
    inStock: boolean;
}

const CATEGORIES = ['Accessories', 'Clothing', 'Electronics', 'Fitness'];

@Component({
    template: `
        <div class="card flex flex-col gap-8">
            <div
                pInfiniteScroll
                itemSelector="[data-product]"
                [loading]="loading()"
                [hasMore]="products().length < 60"
                (scrolled)="load()"
                tabindex="0"
                aria-label="Products"
                role="region"
                class="h-96 overflow-auto border border-surface rounded-border"
            >
                <p-data-view [value]="products()">
                    <ng-template #list let-items>
                        @for (item of items; track item.id; let first = $first) {
                            <div data-product class="flex items-center justify-between gap-4 p-4" [class.border-t]="!first" [class.border-surface]="!first">
                                <div>
                                    <span class="text-sm text-muted-color">{{ item.category }}</span>
                                    <div class="font-medium">{{ item.name }}</div>
                                </div>
                                <div class="flex items-center gap-4">
                                    <p-tag [value]="item.inStock ? 'In stock' : 'Sold out'" [severity]="item.inStock ? 'success' : 'danger'" />
                                    <span class="font-semibold">{{ '$' + item.price }}</span>
                                </div>
                            </div>
                        }
                    </ng-template>
                </p-data-view>
                @if (loading()) {
                    <p class="text-center text-muted-color p-4 m-0">Loading more products...</p>
                }
            </div>
            <div pInfiniteScroll scrollContainer=".p-datatable-table-container" itemSelector="tbody tr" [loading]="tableLoading()" [hasMore]="rows().length < 60" (scrolled)="loadRows()">
                <p-table [value]="rows()" [scrollable]="true" scrollHeight="20rem" [pt]="tablePt" [tableStyle]="{ 'min-width': '30rem' }">
                    <ng-template #header>
                        <tr>
                            <th>Code</th>
                            <th>Name</th>
                            <th>Category</th>
                            <th>Price</th>
                        </tr>
                    </ng-template>
                    <ng-template #body let-row>
                        <tr>
                            <td>{{ 'P-' + row.id }}</td>
                            <td>{{ row.name }}</td>
                            <td>{{ row.category }}</td>
                            <td>{{ '$' + row.price }}</td>
                        </tr>
                    </ng-template>
                </p-table>
                @if (tableLoading()) {
                    <p class="text-center text-muted-color p-2 m-0">Loading more rows...</p>
                }
            </div>
        </div>
    `,
    standalone: true,
    imports: [InfiniteScroll, DataViewModule, TableModule, TagModule]
})
export class InfinitescrollDataviewDemo {
    products = signal<Item[]>([]);

    loading = signal(false);

    rows = signal<Item[]>([]);

    // the scrolling body takes the focus, so that it scrolls with the keyboard
    tablePt = { tableContainer: { tabindex: '0', role: 'region', 'aria-label': 'Products table' } };

    tableLoading = signal(false);

    load() {
        this.loading.set(true);
        setTimeout(() => {
            this.products.update((products) => [...products, ...this.page(products.length, 10)]);
            this.loading.set(false);
        }, 500);
    }

    loadRows() {
        this.tableLoading.set(true);
        setTimeout(() => {
            this.rows.update((rows) => [...rows, ...this.page(rows.length, 15)]);
            this.tableLoading.set(false);
        }, 500);
    }

    page(start: number, size: number): Item[] {
        return Array.from({ length: size }, (_, i) => {
            const id = start + i + 1;
            return { id, name: `Product ${id}`, category: CATEGORIES[id % CATEGORIES.length], price: 10 + ((id * 37) % 90), inStock: id % 5 !== 0 };
        });
    }
}
```

## Load More Button

Infinite scrolling alone is hard to use with a keyboard: the content after the list, like a footer, moves away each time a page is added, and a page loads only when the end of the list is scrolled into view. With manual , scrolling loads nothing and a button calls loadMore() , reached through the template reference #feed="pInfiniteScroll" . Binding manual to an expression gives the best of both: here the first three pages load by scrolling, then the button takes over. After a load from the button, the focus moves to the first new story, so that keyboard and screen reader users continue reading where the new content starts.

```typescript
import { Component, ElementRef, afterNextRender, computed, inject, Injector, signal, viewChild } from '@angular/core';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { InfiniteScroll } from '@exhaustive-ui/core/infinitescroll';

interface Story {
    id: number;
    title: string;
}

@Component({
    template: `
        <div class="card">
            <div
                #list
                pInfiniteScroll
                #feed="pInfiniteScroll"
                itemSelector="article"
                [manual]="pages() >= 3"
                [loading]="loading()"
                [hasMore]="hasMore()"
                (scrolled)="load($event.manual)"
                class="h-80 overflow-auto border border-surface rounded-border"
            >
                <div role="feed" aria-label="Stories" [attr.aria-busy]="loading()">
                    @for (story of stories(); track story.id) {
                        <article
                            tabindex="0"
                            [attr.aria-labelledby]="'loadmore-story-' + story.id"
                            [attr.aria-posinset]="story.id"
                            [attr.aria-setsize]="hasMore() ? -1 : stories().length"
                            class="px-4 py-3 border-b border-surface focus-visible:outline-2 focus-visible:outline-primary"
                        >
                            <span [id]="'loadmore-story-' + story.id" class="font-medium">{{ story.title }}</span>
                        </article>
                    }
                </div>
                <div class="flex justify-center p-4">
                    @if (!hasMore()) {
                        <span class="text-muted-color">No more stories</span>
                    } @else if (feed.manual()) {
                        <p-button [label]="loading() ? 'Loading...' : 'Load more stories'" [loading]="loading()" (onClick)="feed.loadMore()" />
                    } @else if (loading()) {
                        <span class="text-muted-color">Loading...</span>
                    }
                </div>
            </div>
        </div>
    `,
    standalone: true,
    imports: [InfiniteScroll, ButtonModule]
})
export class InfinitescrollLoadmoreDemo {
    private list = viewChild.required<ElementRef<HTMLElement>>('list');

    private injector = inject(Injector);

    stories = signal<Story[]>([]);

    loading = signal(false);

    pages = computed(() => Math.ceil(this.stories().length / 8));

    hasMore = computed(() => this.stories().length < 64);

    load(manual: boolean) {
        this.loading.set(true);
        const first = this.stories().length + 1;
        setTimeout(() => {
            this.stories.update((stories) => [...stories, ...Array.from({ length: 8 }, (_, i) => ({ id: first + i, title: `Story ${first + i}` }))]);
            this.loading.set(false);
            if (manual) {
                afterNextRender(() => this.list().nativeElement.querySelector<HTMLElement>(`[aria-posinset="${first}"]`)?.focus(), { injector: this.injector });
            }
        }, 500);
    }
}
```

## Versus VirtualScroller

InfiniteScroll and the lazy mode of the VirtualScroller both load data while the user scrolls, but they solve different problems. InfiniteScroll appends pages to a list that renders all of its items, so the DOM grows with every page. The Scroller renders only the rows in view, with a fixed item size, and asks for the rows of any range the user jumps to, so it stays fast with hundreds of thousands of rows. Choose InfiniteScroll for feeds, search results, galleries, chats and lists of a few hundred to a few thousand items of varying size, read from start to end. Choose the Scroller for very long uniform lists or tables where the user jumps around and only the visible rows should exist in the DOM. Choose a paginator when users need to come back to a known page.

```typescript
import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';

@Component({
    template: `
        <div class="doc-tablewrapper" tabindex="0">
            <table class="doc-table">
                <thead>
                    <tr>
                        <th>Feature</th>
                        <th>InfiniteScroll</th>
                        <th>Scroller lazy loading</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Rendered items</td>
                        <td>All the items loaded so far</td>
                        <td>Only the visible rows and a buffer</td>
                    </tr>
                    <tr>
                        <td>Item size</td>
                        <td>Any, variable, images, cards, grids</td>
                        <td>Fixed, given with <i>itemSize</i></td>
                    </tr>
                    <tr>
                        <td>Total count</td>
                        <td>Not needed, <i>hasMore</i> says when to stop</td>
                        <td>Needed to size the scrollbar</td>
                    </tr>
                    <tr>
                        <td>Data access</td>
                        <td>Next page from a cursor or an offset, in order</td>
                        <td>Any range, out of order</td>
                    </tr>
                    <tr>
                        <td>Reverse loading</td>
                        <td>Yes, with the scroll position kept</td>
                        <td>No</td>
                    </tr>
                    <tr>
                        <td>Browser find, links to items, printing</td>
                        <td>Work on everything loaded</td>
                        <td>Only on the rendered rows</td>
                    </tr>
                    <tr>
                        <td>Works with</td>
                        <td>Any list: &#64;for, DataView, Listbox, Table without virtual scrolling</td>
                        <td>p-scroller, and the virtual scroll option of Table, Listbox, Select...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    `,
    standalone: true,
    imports: [RouterLink]
})
export class InfinitescrollScrollerDemo {
}
```

## Accessibility

Screen Reader Mark the list up with the WAI-ARIA feed pattern : the container has the feed role and a label, each item is an article that can take the focus, labelled by its title, with aria-posinset for its position and aria-setsize for the total, or -1 while it is unknown. The directive sets aria-busy="true" on its host while loading is true, so that assistive technologies wait for the new page before reading the changes. A polite live region next to the host announces "Loading more items" when a page is asked for, then "10 items loaded" when the new items are in the list, and "End of the list" when hasMore becomes false. The texts are replaced through labels , where {{ '{' }}count{{ '}' }} stands for the number of new items, and announce turns the announcements off when the application makes its own.

## Infinite Scroll

InfiniteScroll asks for more content when the end of a list comes within a distance of the edge of its scroll container or of the viewport. It is based on IntersectionObserver and has no dependency.

### Props

| Name | Type | Default | Description |
|------|------|---------|-------------|
| dt | Object | undefined | Defines scoped design tokens of the component. |
| unstyled | boolean | undefined | Indicates whether the component should be rendered without styles. |
| pt | any | undefined | Used to pass attributes to DOM elements inside the component. |
| ptOptions | PassThroughOptions | undefined | Used to configure passthrough(pt) options of the component. |
| distance | string \| number | 200 | Distance from the end of the list at which more content is asked for: a number of pixels, or a string with a px or % unit (a percentage of the height of the scroll container). |
| direction | InfiniteScrollDirection | 'down' | Side of the list where the content is loaded:  `down`  appends pages at the end and emits scrolled,  `up`  prepends older items at the start, like the history of a chat, emits scrolledUp and keeps the scroll position stable. |
| scrollWindow | boolean | false | Whether the page itself scrolls instead of a container. |
| scrollContainer | InfiniteScrollContainer | - | Scroll container of the list, an element or a CSS selector. By default the host when it scrolls, otherwise its nearest scrolling ancestor, otherwise the page. |
| disabled | boolean | false | When present, no content is asked for. |
| loading | boolean | false | Whether a page is loading. Nothing is emitted while it is true, aria-busy is set on the host, and the end of the list is checked again when it goes back to false. |
| hasMore | boolean | true | Whether there is more content to load. Set it to false at the end of the list to stop asking. |
| manual | boolean | false | When present, scrolling does not load anything: the content is loaded with a load more button that calls loadMore(). |
| throttle | number | 150 | Minimum time in milliseconds between two loads asked by scrolling. |
| itemSelector | string | - | CSS selector of the items of the list, used to count them, keep the scroll position and move the focus. By default the direct children of the host. |
| keyboardNavigation | boolean | true | Whether Page Down, Page Up, Ctrl+Home and Ctrl+End move the focus between the items, as in the WAI-ARIA feed pattern. Page Down on the last item loads more. |
| announce | boolean | true | Whether loads are announced to screen readers through a polite live region. |
| labels | Partial<InfiniteScrollLabels> | - | Texts announced to screen readers, merged with the defaults.  `{count}`  is replaced with the number of new items. |

### Emits

| Name | Parameters | Description |
|------|------------|-------------|
| scrolled | event: InfiniteScrollEvent | Emitted when the end of the list comes within distance and more items are needed, in the down direction. |
| scrolledUp | event: InfiniteScrollEvent | Emitted when the start of the list comes within distance and older items are needed, in the up direction. |

### Methods

| Name | Parameters | Return Type | Description |
|------|------------|-------------|-------------|
| loadMore |  | void | Asks for more content now, whatever the scroll position: call it from a load more button. Nothing is emitted while disabled, loading or without more content. |
| check |  | void | Checks again whether the end of the list is within distance, after a change the directive cannot see, like a container resized by the application. |
| scrollToEnd |  | void | Scrolls the container to the end of the list, the newest message of a chat for example. |
| getItems |  | void | Items of the list. |

