Server-side pagination in Angular tables

Loading every record into an Angular table is convenient for a demo and painful in production. A sales list with 80,000 customers can lock up the browser, consume unnecessary memory and make each filter feel sluggish. Server-side pagination solves the problem by transferring only the rows visible for the current page while keeping the complete result count available to the paginator.

The key is to treat pagination as an API contract, not as a cosmetic setting on a table. The client asks for a page, sort order and optional filter; the server performs the database query and returns both the rows and metadata. That division of responsibility lets an Angular table feel immediate for users in Sydney or Melbourne without placing an enormous query on the database. Neither side should assume it owns all records: the browser never downloads the complete collection, and the API never returns more than the agreed page size.

Designing a stable pagination contract

Agree on a zero-based pageIndex, a positive pageSize, a sortable field and a direction such as asc or desc. A search term can be another optional parameter. Keeping the parameter names identical across the Angular service, ASP.NET Core controller and SQL query removes ambiguity and makes the request easy to inspect in browser developer tools.

The response should contain the current rows plus enough metadata to redraw the paginator after navigation or a refresh:

interface CustomerPage {
  items: Customer[];
  total: number;
  pageIndex: number;
  pageSize: number;
}

total is the count after filters but before paging. Define whether it is exact or deliberately capped, and reject invalid page sizes rather than silently accepting a request for an entire table. The server should also clamp an excessive page index to the final available page or return a clear error that the client can recover from.

For very large datasets, calculate the count with a separate, indexed query so it cannot dominate response time. If the count is approximate, expose that contract explicitly and use a next/previous or cursor-based pager rather than pretending that a numbered pager can be exact.

Connecting Angular to the server

Angular's HttpClient handles query parameters cleanly through HttpParams. Ensure the application provides HttpClient with provideHttpClient() or an equivalent provider, then keep URL construction in a service:

interface CustomerQuery {
  pageIndex: number;
  pageSize: number;
  sortField: string;
  sortDirection: 'asc' | 'desc';
  search?: string;
}

@Injectable({ providedIn: 'root' })
export class CustomerApi {
  private readonly http = inject(HttpClient);

  getPage(query: CustomerQuery): Observable<CustomerPage> {
    let params = new HttpParams()
      .set('pageIndex', query.pageIndex)
      .set('pageSize', query.pageSize)
      .set('sort', query.sortField)
      .set('direction', query.sortDirection);

    if (query.search?.trim()) {
      params = params.set('search', query.search.trim());
    }

    return this.http.get<CustomerPage>('/api/customers', { params });
  }
}

Keep transport concerns in this service and return a typed observable to the component. This makes the table easier to test with Angular's HttpTestingController and gives error handling, authentication and request cancellation a single boundary. Centralising the boundary also keeps bearer-token headers and request-correlation identifiers consistent, while interceptors can report failures without contaminating the presentation layer.

Steven McLintock publishes broader Angular and .NET articles on Kilt and Code, so that site is a useful companion when the data layer is ASP.NET Core. For a production endpoint, validate the requested sort field against an allow-list on the server; interpolating an arbitrary client value into an ORDER BY clause can create a serious injection risk.

Rendering rows and paginator

Angular Material's table and paginator can display the server response without taking ownership of the records. Bind the current items collection as the data source, then bind total to the paginator length:

@if (page$ | async; as page) {
  <table mat-table [dataSource]="page.items">
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef>Customer</th>
      <td mat-cell *matCellDef="let customer">{{ customer.name }}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let row; columns: columns"></tr>
  </table>

  <mat-paginator
    [length]="page.total"
    [pageIndex]="page.pageIndex"
    [pageSize]="page.pageSize"
    [pageSizeOptions]="[25, 50, 100]"
    (page)="changePage($event)" />
}

Import the standalone AsyncPipe, MatTableModule and MatPaginatorModule, define columns and update the query in changePage. Because pageIndex comes from the response, the control remains correct after a browser refresh or a direct link to a particular page. Give the paginator an accessible label, announce result changes through an aria-live region, and preserve keyboard focus when rows refresh.

Show loading, empty and error states as separate conditions. A skeleton row can occupy the table while the first request runs, while an empty state should explain whether there are no records or no matches for the active filter. For Australian users, format currency as A$1,250.00, state clearly whether prices include the 10% GST, and use the DD/MM/YYYY date convention. Add an explicit AEST, AEDT or ACST label when a displayed date matters across states.

Coordinating sorting, filtering and requests

Sorting and filtering change which records exist, so they also change the correct page. A new search term must normally return to page zero; keeping page seven would often produce an empty table even though matching customers exist. The same rule applies when a filter removes most of the result set.

A small reactive query stream can keep those rules in one place:

private readonly query$ = new BehaviorSubject<CustomerQuery>({
  pageIndex: 0,
  pageSize: 25,
  sortField: 'name',
  sortDirection: 'asc'
});

readonly page$ = this.query$.pipe(
  switchMap(query => this.api.getPage(query)),
  shareReplay({ bufferSize: 1, refCount: true })
);

switchMap unsubscribes from the previous request when a new query arrives, preventing a slower early response from overwriting a faster later one. Use a separate debounced control stream for text search, apply distinctUntilChanged, and reset the page index in the same update. Catch transport errors at the stream boundary, expose a retry action and keep the last successful metadata separate from the error view.

Mirror meaningful query state in the URL if users should be able to share a filtered view or use browser Back and Forward. Serialise only stable, validated values and restore them during startup; guard the router stream so restoring state does not emit duplicate requests.

Reliability recommendations for Angular tables

A server-backed table works best when the server owns ordering, counting and limits while the client owns presentation and interaction. Before release, use this practical checklist:

Include the page size and sort keys in structured request logs so slow queries can be traced without logging sensitive customer data. If the count is capped, a conventional numbered paginator cannot reliably navigate the unseen results; use next/previous controls or a cursor-based design instead.

At scale, ask whether offset pagination is appropriate. SQL Server's OFFSET and FETCH NEXT syntax is straightforward, but deep pages can force the database to count and discard many rows. Keyset pagination using the last seen sort value and identifier is steadier for infinite-scroll feeds, although it changes the pager model. A quick squiz at real data volumes can reveal which approach the team actually needs.

For Australian deployments, run the API in a Sydney or Melbourne cloud region when data residency permits, and account for Brisbane's AEST alongside Sydney's AEST and AEDT during daylight-saving changes. Australian software teams often combine Angular front ends with ASP.NET Core, C# and SQL Server, particularly in regulated enterprises, so a backend-agnostic contract also suits smaller businesses without bespoke infrastructure. Support handovers can cross Perth and Adelaide too, making explicit UTC offsets more useful than vague labels such as local time.

Ship a small tested version

Treat the first release as a narrow contract with observable behaviour. Test direct access to the first, middle and final pages; a filter that returns fewer rows than one page; an invalid page size; and rapid sorting or typing that produces competing requests. Confirm that the row count, page index and total count agree with the API response in every state.

Run contract tests against a non-production endpoint, then observe the API and UI together in a browser. This catches mismatched parameter names and date or currency formatting that isolated unit tests can miss.

Then start with a conventional page size of 25, wire the server contract and release the smallest tested version to users. Measure request latency, error rates and common page sizes from real traffic, then tune the endpoint with evidence. Build the first page today, release it to a small user group and let measured usage guide the next iteration.