skip to content

An Angular Material inventory table's catalogue is too large to load into the browser; how do you page and sort it on the server with `MatSort` and `MatPaginator`?

level: seniorimportance: should knowfreq 42%

answer

  1. MatTableDataSource assumes all rows
  2. connect() returns the current page
  3. merge sortChange and page events
  4. length comes from the server total
  5. reset pageIndex when order changes

basics

~20 s

Implement a DataSource whose connect() listens to MatSort.sortChange, MatPaginator.page and the filter, fetches only the requested page from the server, and sets the paginator's length to the server's total. Do not attach them to a MatTableDataSource holding one page.

solid answer

~50 s

`MatTableDataSource` assumes it holds every row: it sorts and slices its own array and sets the paginator's `length` to the rows it holds, so one 50-row page reads as `1 – 50 of 50`, and any page index above zero slices past the end and renders nothing. For a catalogue that stays on the server, extend `DataSource` from `@angular/cdk/collections`. In `connect()`, merge `sort.sortChange`, `paginator.page` and a filter stream, start with one emission, and `switchMap` to an API call built from `sort.active`, `sort.direction`, `paginator.pageIndex` and `paginator.pageSize`. When the response arrives, set `paginator.length` to the server's total and emit the page's rows. When the sort or filter changes, set `pageIndex` back to 0 first, because the old page number means nothing under the new order. Track a loading flag, catch errors, and use `trackBy` on the SKU.

code

ts · 31 lines
ts
import {signal} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {BehaviorSubject, Observable, merge, of} from 'rxjs';
import {catchError, map, skip, startWith, switchMap, tap} from 'rxjs/operators';

export class SkuPageSource extends DataSource<Sku> {
  readonly loading = signal(false);
  private readonly query = new BehaviorSubject('');

  constructor(private api: InventoryApi, private sort: MatSort, private paginator: MatPaginator) { super(); }

  set filter(value: string) { this.query.next(value); }

  connect(): Observable<readonly Sku[]> {
    const reset = merge(this.sort.sortChange, this.query.pipe(skip(1))).pipe(tap(() => (this.paginator.pageIndex = 0)));
    return merge(reset, this.paginator.page).pipe(
      startWith(null),
      tap(() => this.loading.set(true)),
      switchMap(() => this.api.page({
        page: this.paginator.pageIndex, size: this.paginator.pageSize,
        sort: this.sort.active, dir: this.sort.direction, q: this.query.value,
      }).pipe(catchError(() => of({items: [] as Sku[], total: 0})))),
      tap(res => { this.loading.set(false); this.paginator.length = res.total; }),
      map(res => res.items),
    );
  }

  disconnect() { this.query.complete(); }
}

go deeper

for a junior

Recall that MatTableDataSource keeps every row in the browser, and that a large server-held catalogue needs a data source that fetches one page at a time.

for a middle

Explain the connect and disconnect contract, which MatSort and MatPaginator values form the request, and why paginator.length must come from the server.

for a senior

Show the production details: resetting to page one on sort or filter, cancelling stale requests, keeping the stream alive on errors, loading state, and trackBy for stable rows.

for a principal

Decide the paging model the screen and API share, numbered pages with a total or forward-only, and what the paginator UI can honestly show under each.

## Why MatTableDataSource is the wrong tool here `MatTableDataSource` is built for **client-side** data. Its documentation says it is not equipped for server-side interactions. Once you attach a `MatSort` and a `MatPaginator`, it: - sorts its own array, which would reorder only the 50 rows you fetched; - overwrites `paginator.length` with its own filtered count, so the range label reads `1 – 50 of 50` and the next-page button is disabled, hiding the true catalogue size; - slices `pageIndex * pageSize` out of that array, so any page after the first starts past the end of a 50-row array and is **empty**. The fix is to stop asking the browser to sort and page, and let those two components describe a **request** instead. ## The shape of a server-side DataSource `DataSource<T>` from `@angular/cdk/collections` is an abstract class with two methods. The table calls `connect()` and renders whatever arrays the returned Observable emits; it calls `disconnect()` when it is destroyed or the data source is swapped. For the warehouse screen: 1. **Inputs.** The source receives the `MatSort`, the `MatPaginator`, an API client, and a filter stream (debounced keystrokes from the search box). 2. **Reset.** Merge `sort.sortChange` and the filter stream's changes (skip a BehaviorSubject's replayed first value, or it fires a second initial request) and, on each emission, set `paginator.pageIndex = 0`. Setting the property directly does not emit `page`, so this does not trigger a second request. 3. **Trigger.** Merge that reset stream with `paginator.page`, add `startWith(null)` so the first page loads immediately, and `switchMap` to the API call. `switchMap` drops a slow response for a page the user has already left. 4. **Request.** Build it from `sort.active`, `sort.direction` (`'asc'`, `'desc'` or `''` for none), `paginator.pageIndex`, `paginator.pageSize` and the current filter. 5. **Response.** Set `paginator.length` to the total the server reports, so the range label and the next-page button are right, then emit the rows. 6. **Errors and loading.** Catch errors and emit an empty page so the stream survives; expose a `loading` signal for a progress bar. A `*matNoDataRow` then covers both "no matches" and "request failed". ## Client-side versus server-side | Concern | MatTableDataSource | Server-side DataSource | |---|---|---| | Rows held in the browser | all of them | one page | | Sorting | `sortData` over the array | the API's sort parameter | | Filtering | `filterPredicate` per row | the API's query parameter | | `paginator.length` | filtered count, set for you | server total, set by you | | Page change | slice, no network | a new request | ## Details that bite in production - **Sort and paginator must exist.** Create the data source in `ngAfterViewInit`, when `viewChild` queries have resolved, and hold it in a signal bound to `[dataSource]` so the late assignment renders cleanly. The search box then sets `source.filter` on each debounced keystroke. - **Paging index is zero-based.** `pageIndex` 0 is the first page; translate if the API is one-based. - **Row identity.** Each response is a new array of new objects. Without `trackBy`, every page change rebuilds every row; with `trackBy` returning the SKU, a refetch of the same page keeps the existing rows. - **No unsorted state.** If the API has no unsorted order, give `matSort` an initial `matSortActive` and `matSortDirection` and set `matSortDisableClear`, so `direction` never becomes `''` after a third click. - **Wire format.** The paginator models numbered pages and a known total. How the endpoint expresses pages, totals or cursors is the API's contract; the table only needs a page of rows and a total to show. - **Very long pages.** If users want hundreds of rows on one page, rendering cost becomes the problem; windowing the rows is a separate technique. ## Wiring it to the screen In the template, bind `[length]` only if you do not set `paginator.length` from the data source; doing both makes two owners for one number. Give the paginator `pageSizeOptions` that the API accepts, add `matSort` and `mat-sort-header` exactly as for client-side data, and add a `*matNoDataRow` row. The header arrows, the range label and the page buttons all keep working, because they only read the state of `MatSort` and `MatPaginator`, not where the rows came from. ## A simpler variant For small screens you can skip the class: bind `[dataSource]` to an array signal and update it from `(matSortChange)` and `(page)` handlers. The class pays off when the same paging logic is shared across several tables, or when loading state and cancellation need one home.

  • Why does setting paginator.pageIndex = 0 in the reset step not cause a duplicate request?
    `MatPaginator` emits `page` only from its own navigation methods and user interaction, such as `nextPage()` or `firstPage()`. Assigning `pageIndex` directly just updates the value. The fetch is triggered once by the sort or filter emission, and by the time `switchMap` builds the request it already reads index 0.
  • How do you show a progress bar and keep the old rows visible while the next inventory page loads?
    Expose a `loading` signal from the data source, set it before the request and clear it when the response or error arrives, and bind a progress bar to it. Because the Observable only emits when the response lands, the table keeps showing the previous page until then.
  • What should the data source do when the inventory API fails?
    Catch the error inside the `switchMap` and emit an empty page, so the outer stream stays alive and the next sort or page change can retry. Clear the loading flag, record an error state for a message, and let `*matNoDataRow` render the empty table.

  • Attach MatSort and MatPaginator to a MatTableDataSource holding one server page.
  • The paginator works out the total from the rows it is given.
  • Keep the current page number when the user changes the sort column.
  • Setting pageIndex in code emits the page event like a click does.
  • Catching errors outside the switchMap is fine; the stream keeps running.