Build a custom Angular pagination component
Pagination looks simple until a list grows beyond a single screen. A robust page control must handle changing totals, preserve the current position, and remain usable with a keyboard or screen reader. Building one from scratch gives an application full control over its layout and behaviour. Learn more about Voicemeeter Bananaのバス構造を理解して送り先を自由に切り替える応用.
Angular’s component model is a natural fit for this job. Inputs can describe the result set, outputs can report a requested page, and a small computed view model can determine which numbered buttons to display. The component stays independent from any particular API or data-loading library.
This implementation uses standalone components and Angular signals, introduced in Angular 17. The parent keeps ownership of the current page, while the pager emits page-change events. That controlled approach makes URL synchronisation, filtering and test isolation straightforward.
The examples suit Australian products: catalogue pages for shoppers in Sydney and Melbourne, prices in Australian dollars including GST, and Angular clients backed by ASP.NET Core and SQL Server. They also account for variable NBN and mobile connections outside major cities, Brisbane’s AEST/AEDT versus Perth’s AWST, and en-AU day-first dates.
Define the pagination contract
Start with four values: total item count, page size, current page and requested page. The total count comes from the server; page size defines how many records fit on one page; current page drives the active state; requested page notifies the parent that the user wants to move.
Use Angular’s typed input and output APIs rather than mutable properties. Required inputs make missing data visible, while defaults keep simple usage concise. The parent remains the source of truth, so the component does not need to synchronise a private copy of the page.
A narrow contract also separates navigation from data retrieval. It resembles a routing desk where destinations stay independent while a controller chooses the active route. This explanation of Voicemeeter Banana bus routing uses a similar bus-and-send model, although a web pager has a much smaller job.
Create the Angular component
Generate a standalone component with the Angular CLI, then keep its public API small.
npx ng generate component ui/pagination
import {
ChangeDetectionStrategy,
Component,
computed,
input,
output
} from '@angular/core';
type PageItem = number | 'ellipsis';
@Component({
selector: 'app-pagination',
standalone: true,
templateUrl: './pagination.component.html',
styleUrl: './pagination.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PaginationComponent {
readonly totalItems = input.required<number>();
readonly pageSize = input(10);
readonly currentPage = input(1);
readonly pageChange = output<number>();
readonly totalPages = computed(() => {
const count = Math.max(0, Math.floor(this.totalItems()));
const size = Math.max(1, Math.floor(this.pageSize()));
return Math.max(1, Math.ceil(count / size));
});
readonly activePage = computed(() =>
Math.min(
Math.max(1, Math.floor(this.currentPage())),
this.totalPages()
)
);
}
Normalising the values inside computed signals prevents a zero page size or stale current page from breaking the controls. Because the template reads signals, Angular can update only the affected view. The component still needs a guard when the parent passes an invalid page size, which is usually best handled by shared validation.
Build accessible navigation controls
Use a labelled nav element, real buttons and an unordered list. Buttons are keyboard-operable and expose state through aria-current; the active page should also have a non-colour cue so it remains clear to people with low vision.
@if (totalItems() > 0) {
<nav class="pagination" aria-label="Results pagination">
<button
class="previous"
type="button"
[disabled]="activePage() === 1"
(click)="goTo(activePage() - 1)"
>
Previous
</button>
<ul>
@for (item of visiblePages(); track $index) {
@if (item === 'ellipsis') {
<li class="ellipsis">
<span aria-hidden="true">…</span>
<span class="sr-only">More pages</span>
</li>
} @else {
<li>
<button
type="button"
[class.active]="item === activePage()"
[attr.aria-current]="item === activePage() ? 'page' : null"
[attr.aria-label]="'Go to page ' + item"
(click)="goTo(item)"
>
{{ item }}
</button>
</li>
}
}
</ul>
<button
class="next"
type="button"
[disabled]="activePage() >= totalPages()"
(click)="goTo(activePage() + 1)"
>
Next
</button>
</nav>
}
Keep the selected button, focus outline and hover state visible in CSS. Give touch targets at least 44 pixels and let the list wrap on narrow screens. Add the standard sr-only utility to the stylesheet so assistive text remains available to screen readers while being visually hidden; never use it to hide essential controls.
Calculate a compact page range
A fixed list of page numbers becomes unwieldy with hundreds of results. The computed model below shows a small window around the current page, retains the first and last pages, and inserts an ellipsis where pages have been skipped.
readonly visiblePages = computed<PageItem[]>(() => {
const total = this.totalPages();
const current = this.activePage();
if (total <= 7) {
return Array.from({ length: total }, (_, index) => index + 1);
}
if (current <= 4) {
return [1, 2, 3, 4, 5, 'ellipsis', total];
}
if (current >= total - 3) {
return [
1,
'ellipsis',
total - 4,
total - 3,
total - 2,
total - 1,
total
];
}
return [
1,
'ellipsis',
current - 1,
current,
current + 1,
'ellipsis',
total
];
});
goTo(page: number): void {
const target = Math.min(
Math.max(1, page),
this.totalPages()
);
if (target !== this.activePage()) {
this.pageChange.emit(target);
}
}
Tune the seven-item window to suit the design, but keep the boundary conditions symmetrical. Since previous and next buttons remain available, skipping numbers never blocks access to a page. The parent must apply the emitted value to currentPage; otherwise the controlled component correctly stays where it was.
Connect pagination to an API
A list component should own the request state and pass the server’s total count into the pager. Query parameters make a page shareable and allow browser navigation to restore the same result set.
<app-pagination
[totalItems]="totalItems()"
[pageSize]="pageSize"
[currentPage]="page()"
(pageChange)="loadPage($event)"
/>
readonly page = signal(1);
readonly pageSize = 10;
readonly totalItems = signal(0);
loadPage(page: number): void {
this.http.get<PagedResult>('/api/orders', {
params: { page, pageSize: this.pageSize }
}).subscribe({
next: result => {
this.orders.set(result.items);
this.totalItems.set(result.totalItems);
this.page.set(page);
}
});
}
Cancel an old request when another begins, or use a single reactive stream with switchMap, so a slow response cannot overwrite newer results. When filters change, reset to page one; when the total shrinks, clamp the current page to the new last page. Store the page in the query string with Router if users should be able to bookmark and share filtered results.
Test the pagination behaviour
Treat the pager as a small state machine. Tests should cover the emitted page, disabled boundaries, the active page’s ARIA state and the compact range around the beginning, middle and end of a collection.
it('emits the requested page', () => {
const emitted: number[] = [];
fixture.componentInstance.pageChange.subscribe(
page => emitted.push(page)
);
fixture.componentRef.setInput('totalItems', 42);
fixture.componentRef.setInput('pageSize', 10);
fixture.componentRef.setInput('currentPage', 1);
fixture.detectChanges();
const previous = fixture.nativeElement.querySelector(
'button.previous'
) as HTMLButtonElement;
const next = fixture.nativeElement.querySelector(
'button.next'
) as HTMLButtonElement;
expect(previous.disabled).toBeTrue();
next.click();
expect(emitted).toEqual([2]);
});
Create the fixture through TestBed and import the standalone component in the test module. Query elements by class or accessible role rather than brittle text positions. Add cases for a single page, an empty collection, a reduced total count and clicking the current page, which should not emit a redundant event.
Use the pager in a production application
Decide whether page size is fixed by the API or selectable by the user. If it changes, expose a separate page-size output and reset to page one; mixing that choice into the page-change event makes the parent harder to reason about. A results summary such as “Showing 11–20 of 347” gives useful context without replacing the numbered controls.
Keep server-side pagination for large datasets. The browser should receive only the rows needed for the current page, while the API returns the unfiltered total used to calculate page boundaries. For frequently visited catalogues, cache stable requests briefly and invalidate them when products, prices or stock change.
Finally, test the component in the application’s real theme. Responsive layouts, focus order, translated labels and keyboard navigation often reveal problems hidden by unit tests. A design-system wrapper can apply shared spacing and typography, while the component continues to own page calculations and user interactions.
Create the component in a feature branch, connect it to one real API-backed list, and add the boundary tests before reusing it elsewhere. That small slice proves the contract, accessibility and data flow together.
Then publish the implementation through Kilt and Code with the decisions and trade-offs documented, so another developer can copy the pattern, adapt the styling and ship a dependable Angular pager without rebuilding the same logic.