# Pagination

Navigate pages with buttons, links, or your router.

```angular-ts title="basic.ts"
import { Component } from "@angular/core"
import {
  LucideChevronLeft,
  LucideChevronRight,
  LucideEllipsis,
} from "@lucide/angular"
import { useLog } from "./log"
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/angular/pagination"

@Component({
  imports: [
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
    LucideChevronLeft,
    LucideChevronRight,
    LucideEllipsis,
  ],
  template: `
    <nav
      uiPagination
      aria-label="Pagination"
      [pageCount]="10"
      (beforePageChange)="
        log('Page ' + $event.value + ' (' + $event.reason + ')')
      "
    >
      <ul uiPaginationList #paginationList="uiPaginationList">
        <li uiPaginationItem>
          <button uiPaginationPrevious data-variant="ghost">
            <svg lucideChevronLeft></svg>
            <span data-slot="visually-hidden">Previous</span>
          </button>
        </li>
        @for (item of paginationList.state().items; track item) {
          <li uiPaginationItem>
            @if (typeof item === "number") {
              <button
                uiPaginationLink
                data-variant="ghost"
                [page]="item"
              ></button>
            } @else {
              <span uiPaginationEllipsis>
                <svg lucideEllipsis></svg>
              </span>
            }
          </li>
        }
        <li uiPaginationItem>
          <button uiPaginationNext data-variant="ghost">
            <span data-slot="visually-hidden">Next</span>
            <svg lucideChevronRight></svg>
          </button>
        </li>
      </ul>
    </nav>
  `,
})
class Example {
  readonly log = useLog()
}

export { Example }
```

Choose a page, or use Previous and Next. The console logs each page and its reason, and the step at either end stays focusable as a button.

## Installation

```bash
npm install @ui-sdk/angular @ui-sdk/core
```

## Composition

Use the following composition to build Pagination:

```text
uiPagination
└── uiPaginationList
    ├── uiPaginationItem
    │   └── uiPaginationPrevious
    ├── uiPaginationItem
    │   └── uiPaginationLink
    ├── uiPaginationItem
    │   └── uiPaginationEllipsis
    ├── uiPaginationItem
    │   └── uiPaginationLink
    └── uiPaginationItem
        └── uiPaginationNext
```

Name the navigation with `aria-label`, then put the page links and steps in a list.

Read the list's state from a template reference. Its `items` contains page numbers and the strings `"ellipsis-start"` and `"ellipsis-end"`. Render a link for each number and an ellipsis for each gap. Track entries by the item itself so a page link keeps its element as the range moves.

`uiPaginationLink` shows its page number when you leave it empty. The current link gets `aria-current="page"` and `data-current`. `uiPaginationEllipsis` shows “…” and is hidden from screen readers.

Give Previous, Next, First, and Last text or an `aria-label`. At an end, a step gets `aria-disabled="true"` and `data-disabled` and stops changing the page. As a button, it stays in the tab order. Set `disabled` on the root to do the same for every page and step, like while results load. A controller still changes the page.

## Usage

Import the parts and put them together:

```ts
import { Component } from "@angular/core"
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/angular/pagination"

@Component({
  selector: "app-example",
  imports: [
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
  ],
  template: `
    <nav uiPagination aria-label="Pagination" [pageCount]="10">
      <ul uiPaginationList #list="uiPaginationList">
        <li uiPaginationItem>
          <button uiPaginationPrevious>Previous</button>
        </li>
        @for (item of list.state().items; track item) {
          <li uiPaginationItem>
            @if (typeof item === "number") {
              <button uiPaginationLink [page]="item"></button>
            } @else {
              <span uiPaginationEllipsis></span>
            }
          </li>
        }
        <li uiPaginationItem>
          <button uiPaginationNext>Next</button>
        </li>
      </ul>
    </nav>
  `,
})
class Example {}

export { Example }
```

## Total and Page Size

Instead of `pageCount`, pass `total`, how many items there are, and `pageSize`, how many fit on a page (10 by default). Pagination calculates the page count, with a minimum of one. This example resets to page 1 when the page size changes.

A page past the end, like after the count shrinks, reads as the last page.

```angular-ts title="total.ts"
import { Component, computed, signal } from "@angular/core"
import {
  LucideChevronLeft,
  LucideChevronRight,
  LucideEllipsis,
} from "@lucide/angular"
import { useLog } from "./log"
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/angular/pagination"

@Component({
  imports: [
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
    LucideChevronLeft,
    LucideChevronRight,
    LucideEllipsis,
  ],
  template: `
    <div data-slot="stack">
      <div data-slot="row">
        <p>Showing {{ first() }}–{{ last() }} of {{ total }}</p>
        <label data-slot="label">
          Rows per page
          <select [value]="pageSize()" (change)="onPageSizeChange($event)">
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </select>
        </label>
      </div>
      <nav
        uiPagination
        [(page)]="page"
        aria-label="Pagination"
        [total]="total"
        [pageSize]="pageSize()"
        (beforePageChange)="log('Page ' + $event.value)"
      >
        <ul uiPaginationList #paginationList="uiPaginationList">
          <li uiPaginationItem>
            <button uiPaginationPrevious data-variant="ghost">
              <svg lucideChevronLeft></svg>
              <span data-slot="visually-hidden">Previous</span>
            </button>
          </li>
          @for (item of paginationList.state().items; track item) {
            <li uiPaginationItem>
              @if (typeof item === "number") {
                <button
                  uiPaginationLink
                  data-variant="ghost"
                  [page]="item"
                ></button>
              } @else {
                <span uiPaginationEllipsis>
                  <svg lucideEllipsis></svg>
                </span>
              }
            </li>
          }
          <li uiPaginationItem>
            <button uiPaginationNext data-variant="ghost">
              <span data-slot="visually-hidden">Next</span>
              <svg lucideChevronRight></svg>
            </button>
          </li>
        </ul>
      </nav>
    </div>
  `,
})
class Example {
  readonly log = useLog()

  readonly page = signal(2)

  readonly pageSize = signal(20)

  readonly total = 95

  readonly first = computed(() => (this.page() - 1) * this.pageSize() + 1)

  readonly last = computed(() =>
    Math.min(this.page() * this.pageSize(), this.total)
  )

  onPageSizeChange(event: Event) {
    const { value } = event.target as HTMLSelectElement
    this.pageSize.set(Number(value))
    this.page.set(1)
    this.log(`${value} rows per page`)
  }
}

export { Example }
```

Choose a page, then change Rows per page. The console logs each change, and a new size starts again at page 1.

## Simple

With only a few pages, the range has no gaps, so you can write the links out and leave the steps off.

```angular-html
<nav uiPagination aria-label="Pagination" [pageCount]="5">
  <ul uiPaginationList>
    @for (page of [1, 2, 3, 4, 5]; track page) {
      <li uiPaginationItem>
        <button uiPaginationLink [page]="page"></button>
      </li>
    }
  </ul>
</nav>
```

## Links

Pass `getHref` to map each page to a URL, and put page links and steps on `<a>` elements. Each gets its page's `href`, with the check Angular gives an `[href]` binding. Without `getHref`, put them on `<button>` elements.

```ts
import { Component } from "@angular/core"
import { Pagination } from "@ui-sdk/angular/pagination"

@Component({
  selector: "app-example",
  imports: [Pagination],
  template: `
    <nav
      uiPagination
      aria-label="Pagination"
      [pageCount]="10"
      [getHref]="getHref"
    >
      ...
    </nav>
  `,
})
class Example {
  readonly getHref = (page: number) => `/posts?page=${page}`
}

export { Example }
```

Server-rendered anchors work before JavaScript loads. A normal click changes the page and follows the URL. Modifier clicks and middle clicks leave pagination state alone so the browser can open the link elsewhere.

A step at its end loses its `href` and leaves the tab order, but keeps focus if it already had it. During navigation, its original `href` stays in place so Next cannot accidentally follow the next page's URL.

## Router Links

Page on the client with the Angular router. With `getHref`, links and steps on `<a>` elements have real URLs. Cancel the change in `(beforePageChange)` and navigate yourself: a canceled change calls `preventDefault()` on the click, so the browser stays on the page.

Read the page from the URL, like your router's search params, so the route [controls](#controlled) the pagination.

```ts
import { Component, inject } from "@angular/core"
import { toSignal } from "@angular/core/rxjs-interop"
import { ActivatedRoute, Router } from "@angular/router"
import { map } from "rxjs"
import {
  Pagination,
  type PaginationPageChange,
} from "@ui-sdk/angular/pagination"

@Component({
  selector: "app-example",
  imports: [Pagination],
  template: `
    <nav
      uiPagination
      aria-label="Pagination"
      [pageCount]="10"
      [page]="page()"
      [getHref]="getHref"
      (beforePageChange)="goTo($event)"
    >
      ...
    </nav>
  `,
})
class Example {
  readonly #router = inject(Router)

  readonly page = toSignal(
    inject(ActivatedRoute).queryParamMap.pipe(
      map((params) => Number(params.get("page") ?? 1))
    ),
    { initialValue: 1 }
  )

  readonly getHref = (page: number) => `?page=${page}`

  goTo(change: PaginationPageChange) {
    change.cancel()
    this.#router.navigate([], { queryParams: { page: change.value } })
  }
}

export { Example }
```

## Controlled

Bind `page` with `[(page)]` to control the pagination, and use `(beforePageChange)` for the reason.

```ts
import { Component, signal } from "@angular/core"
import { Pagination } from "@ui-sdk/angular/pagination"

@Component({
  selector: "app-example",
  imports: [Pagination],
  template: `
    <nav uiPagination [(page)]="page" aria-label="Pagination" [pageCount]="10">
      ...
    </nav>
  `,
})
class Example {
  readonly page = signal(1)
}

export { Example }
```

Every change carries a [reason](#reasons): `item-press` for a page, `previous-press`, `next-press`, `first-press` or `last-press` for a step, and `imperative` from a [controller](#controller). Call `$event.cancel()` to keep the page, like while a form has unsaved changes. A canceled change also stops a link from navigating.

## Default Page

`defaultPage` is the page it starts on, when uncontrolled. It's 1 by default.

```angular-html
<nav uiPagination aria-label="Pagination" [pageCount]="10" [defaultPage]="5">
  ...
</nav>
```

## Siblings

`siblings` is how many pages show on each side of the current one, 1 by default. Near an end, the window slides over instead of shrinking, keeping the range length stable. A gap of one page shows that page instead of an ellipsis.

```angular-html
<nav
  uiPagination
  aria-label="Pagination"
  [pageCount]="20"
  [defaultPage]="10"
  [siblings]="2"
>
  ...
</nav>
```

## Boundaries

`boundaries` is how many pages always show at each end, 1 by default.

```angular-html
<nav
  uiPagination
  aria-label="Pagination"
  [pageCount]="20"
  [defaultPage]="10"
  [boundaries]="2"
>
  ...
</nav>
```

## Paging from Anywhere

A [controller](#controller), from `createPaginationController()`, pages the pagination from anywhere, like buttons elsewhere on the page or a keyboard shortcut, without controlling it. Pass it as `controller`.

```ts
import { Component } from "@angular/core"
import {
  Pagination,
  createPaginationController,
} from "@ui-sdk/angular/pagination"

@Component({
  selector: "app-example",
  imports: [Pagination],
  template: `
    <button (click)="pagination.next()">Next Page</button>
    <nav
      uiPagination
      aria-label="Pagination"
      [pageCount]="10"
      [controller]="pagination"
    >
      ...
    </nav>
  `,
})
class Example {
  readonly pagination = createPaginationController()
}

export { Example }
```

## Your Own Markup

`paginationRange({ page, pageCount, siblings, boundaries })` is the range the parts use, as a pure function. It runs anywhere, like on the server, in an email or for a UI that isn't a list of pages. Import it from `@ui-sdk/core/pagination`. Here it keeps a strip of slide dots the same length however many slides there are.

```ts
import { Component, computed, signal } from "@angular/core"
import { paginationRange } from "@ui-sdk/core/pagination"

@Component({
  selector: "app-example",
  template: `
    <div role="group" aria-label="Slides">
      @for (item of items(); track item) {
        @if (typeof item === "number") {
          <button
            [attr.aria-label]="'Slide ' + item"
            [attr.aria-current]="item === slide() ? 'true' : null"
            (click)="slide.set(item)"
          ></button>
        } @else {
          <span aria-hidden="true"></span>
        }
      }
    </div>
  `,
})
class Example {
  readonly slide = signal(1)

  readonly items = computed(() =>
    paginationRange({
      page: this.slide(),
      pageCount: 20,
      siblings: 2,
      boundaries: 1,
    })
  )
}

export { Example }
```

## Custom Rendering

Each directive goes on an element you write. Read a part's state from a template reference: whether a link is `current`, and for a step, the `page` it goes to and whether it's `disabled`.

```angular-ts title="render.ts"
import { Component } from "@angular/core"
import { LucideArrowLeft, LucideArrowRight } from "@lucide/angular"
import {
  Pagination,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
} from "@ui-sdk/angular/pagination"

@Component({
  imports: [
    Pagination,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationList,
    PaginationNext,
    PaginationPrevious,
    LucideArrowLeft,
    LucideArrowRight,
  ],
  template: `
    <nav uiPagination aria-label="Pagination" [pageCount]="10">
      <ul uiPaginationList #list="uiPaginationList">
        <li uiPaginationItem>
          <button
            uiPaginationPrevious
            #previous="uiPaginationPrevious"
            aria-label="Previous page"
            [attr.title]="
              previous.state().disabled
                ? null
                : 'Go to page ' + previous.state().page
            "
          >
            <svg lucideArrowLeft></svg>
            @if (!previous.state().disabled) {
              <span aria-hidden="true">{{ previous.state().page }}</span>
            }
          </button>
        </li>
        @for (item of list.state().items; track item) {
          <li uiPaginationItem>
            @if (typeof item === "number") {
              <button uiPaginationLink #link="uiPaginationLink" [page]="item">
                {{
                  link.state().current
                    ? "Page " + link.state().page
                    : link.state().page
                }}
              </button>
            } @else {
              <span uiPaginationEllipsis></span>
            }
          </li>
        }
        <li uiPaginationItem>
          <button
            uiPaginationNext
            #next="uiPaginationNext"
            aria-label="Next page"
            [attr.title]="
              next.state().disabled ? null : 'Go to page ' + next.state().page
            "
          >
            @if (!next.state().disabled) {
              <span aria-hidden="true">{{ next.state().page }}</span>
            }
            <svg lucideArrowRight></svg>
          </button>
        </li>
      </ul>
    </nav>
  `,
})
class Example {}

export { Example }
```

Choose a page. The current page widens to say Page 3, and each arrow shows the page it goes to.

## Styling

Parts are unstyled. Style them through the attributes they render, which are the same in every framework: `aria-current="page"` or `data-current` on the current page's link, and `aria-disabled` or `data-disabled` on a step at its end.

Each part has a `data-slot`, such as `pagination-link`, and its state attributes are listed under [Data Attributes](#data-attributes). The root, list, items and ellipsis have none.

## Data Attributes

### PaginationLink
`[data-slot="pagination-link"]`

- `data-current`: Present on the current page's link, beside `aria-current="page"`.

### PaginationPrevious
`[data-slot="pagination-previous"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

### PaginationNext
`[data-slot="pagination-next"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

### PaginationFirst
`[data-slot="pagination-first"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

### PaginationLast
`[data-slot="pagination-last"]`

- `data-disabled`: Present on a step at the end it goes to, beside `aria-disabled`. It stays focusable and does nothing.

## API Reference

Each option below is an input on the directive, and each callback an output. A change callback is two outputs: `(beforePageChange)`, with the details and `cancel()`, then `(pageChange)` with the new value alone. Bind `page` with `[(page)]`.

### Pagination

- `page?` (`number`): The current page, from 1. Pass it to control the pagination.
- `defaultPage?` (`number`): The page it starts on, when uncontrolled.
- `(beforePageChange)`: Runs when the page wants to change: a page link (`"item-press"`), the Previous, Next, First or Last part, or a controller (`"imperative"`). `details.cancel()` keeps the page, and stops a link from navigating.
- `pageCount?` (`number`): How many pages there are. Or pass `total` and `pageSize`.
- `total?` (`number`): How many items there are, for `pageCount` from `pageSize`.
- `pageSize?` (`number`): How many items fit on a page, with `total`.
- `siblings?` (`number`): How many pages show on each side of the current one.
- `boundaries?` (`number`): How many pages always show at each end.
- `getHref?` (`((page: number) => string)`): The URL of a page. With it, parts are links: they navigate, open in a new tab with a modifier key, and work before JavaScript loads. Without it, they're buttons.
- `disabled?` (`boolean`): Whether every page and step does nothing, like a step at its end. A controller still pages it.
- `controller?` (`object`): Pages it from anywhere. Create one with `createPaginationController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### PaginationLink

- `page` (`number`): The page the link goes to, from 1.

`uiPaginationList`, `uiPaginationItem`, `uiPaginationPrevious`, `uiPaginationNext`, `uiPaginationFirst`, `uiPaginationLast` and `uiPaginationEllipsis` take no inputs of their own.

### State

What each part's `state()` signal holds, per part.

`uiPagination` and `uiPaginationList`:

- `page` (`number`): The current page, from 1.
- `pageCount` (`number`): How many pages there are.
- `items` (`PaginationRangeItem[]`): The pages to show, with an ellipsis for each gap. Render a PaginationLink or a PaginationEllipsis for each.

`uiPaginationLink`:

- `page` (`number`): The page it goes to, from its `page` prop.
- `current` (`boolean`): Whether it's the current page.

`uiPaginationPrevious`, `uiPaginationNext`, `uiPaginationFirst` and `uiPaginationLast`:

- `page` (`number`): The page it goes to.
- `disabled` (`boolean`): Whether it's at the end it goes to, or the pagination is disabled, so it does nothing.

### Reasons

`$event.reason` says why the page changed.

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `previous-press` (`MouseEvent | KeyboardEvent`): A pagination's or a carousel's Previous part was pressed.
- `next-press` (`MouseEvent | KeyboardEvent`): A pagination's or a carousel's Next part was pressed.
- `first-press` (`MouseEvent | KeyboardEvent`): A pagination's First part was pressed.
- `last-press` (`MouseEvent | KeyboardEvent`): A pagination's Last part was pressed.
- `imperative` (`none`): A controller or `api` call.

### Controller

Create one with `createPaginationController()` and pass it as `controller`.

Every write method takes an optional `{ reason, event }`, passed to `(beforePageChange)`, and returns `false` when the change is canceled or there's nowhere to go.

- `getPage()` (`() => number`): The current page, from 1.
- `getPageCount()` (`() => number`): How many pages there are.
- `setPage(page, options?)` (`(page: number, options?: PaginationChangeOptions | undefined) => boolean`): Goes to a page, clamped to the range. Returns false when canceled or already there.
- `next(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the next page. Returns false on the last page.
- `previous(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the previous page. Returns false on the first page.
- `first(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the first page.
- `last(options?)` (`(options?: PaginationChangeOptions | undefined) => boolean`): Goes to the last page.

### Events

A `before` output emits `{ value, reason, event, cancel() }` before the change, and its plain output follows with the value alone. A bound `page` only updates when `(beforePageChange)` wasn't canceled.

| Binding              | On             | Receives                                                                |
| -------------------- | -------------- | ----------------------------------------------------------------------- |
| `[(page)]`           | `uiPagination` | The current page                                                        |
| `(beforePageChange)` | `uiPagination` | `{ value, reason, cancel() }`: the new page, and the [reason](#reasons) |

## Accessibility

There's no WAI-ARIA pattern for pagination. It follows the common practice: a `navigation` landmark named with `aria-label`, a list of links or buttons, and `aria-current="page"` on the current one. The list keeps the `list` role even when styled without bullets, which Safari would otherwise drop.

### Focus

Steps rendered as buttons stay focusable at the ends. A clicked page link keeps focus as the range moves; the primitive also tries to restore focus to that page or step if rendering replaces its element. Key range entries by their value rather than their index.

### Tested Behavior

Every line below is an automated test.

- The pagination is a named navigation landmark with a list of pages.
- The first page is current to start with, or the default page.
- Pressing a page goes there.
- Enter on a focused page goes there.
- Space on a focused page goes there.
- Next and Previous step one page.
- First and Last go to the ends.
- First and Previous say they're disabled on the first page, and do nothing.
- Next and Last say they're disabled on the last page, and do nothing.
- A single page has nothing to step to.
- Siblings and boundaries widen the range.
- Ellipses are hidden from screen readers.
- With getHref, pages and steps are links to their pages.
- A link at an end has no href and says it's disabled.
- Pressing a link goes to its page and follows it.
- A change can be canceled.
- A canceled change stops a link from navigating.
- The controller pages it from outside.
- A controlled pagination follows its owner. React and Vue only.

Runs in React, Vue and web components.

Beyond the baseline:

- Pressing Next onto the last page keeps focus on Next.
- Pressing Previous onto the first page keeps focus on Previous.
- Paging through every page with the keyboard never loses focus.
- Pressing a page keeps focus on it while the range moves around it.
- Focus comes back to the same part when the list renders again from scratch. React and Vue only.
- The list has the same number of entries on every page, so nothing shifts under the pointer.
- A gap of one page shows that page instead of an ellipsis.
- A link pressed with a modifier opens elsewhere and leaves the page as it is.
- The list keeps its list role when styled without bullets.
- Steps at the ends stay in the tab order and say they're disabled.
- A Next link goes to the next page, not past it, even after the page renders again.
- A Next link onto the last page still goes there, though it ends there.

Runs in React, Vue and web components.

Screen readers hear the same thing in each tested framework, recorded by a virtual screen reader:

- Announcements while paging with a keyboard.

Runs in React, Vue and web components.
