skip to content

How do you connect `MatSort` and `MatPaginator` to Angular Material's `MatTableDataSource`, and in what order does it filter, sort and page rows?

level: middleimportance: must knowfreq 55%

answer

  1. assign after the view exists
  2. dataSource.sort and dataSource.paginator
  3. filter, then sort, then slice
  4. paginator length set for you
  5. replace data, not the data source

basics

~20 s

Put matSort on the table and mat-sort-header on header cells, then assign the MatSort and MatPaginator instances to dataSource.sort and dataSource.paginator once the view exists. The data source filters, sorts the filtered rows, then slices the current page.

solid answer

~40 s

Import `MatSortModule` and `MatPaginatorModule`, add `matSort` to the table and `mat-sort-header` to each sortable header cell (its id defaults to the column name), and place a `<mat-paginator>` after the table. Query both with `viewChild` and assign them in `ngAfterViewInit`: `dataSource.sort = this.sort()` and `dataSource.paginator = this.paginator()`. From then on `MatTableDataSource` runs a fixed pipeline: it applies `filter` through `filterPredicate`, sorts a copy of the filtered rows with the active `MatSort` state, and slices out `pageIndex * pageSize`. It also sets the paginator's `length` to the filtered count. When new data arrives, assign it to `dataSource.data`; do not create a new `MatTableDataSource`, which drops the sort and paginator wiring.

code

ts · 39 lines
ts
import {AfterViewInit, Component, viewChild} from '@angular/core';
import {MatTableDataSource, MatTableModule} from '@angular/material/table';
import {MatSort, MatSortModule} from '@angular/material/sort';
import {MatPaginator, MatPaginatorModule} from '@angular/material/paginator';

interface Sku { sku: string; stock: number; }

@Component({
  selector: 'app-inventory',
  imports: [MatTableModule, MatSortModule, MatPaginatorModule],
  template: `
    <table mat-table [dataSource]="dataSource" matSort matSortActive="stock" matSortDirection="asc">
      <ng-container matColumnDef="sku">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>SKU</th>
        <td mat-cell *matCellDef="let row">{{ row.sku }}</td>
      </ng-container>
      <ng-container matColumnDef="stock">
        <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by stock level">Stock</th>
        <td mat-cell *matCellDef="let row">{{ row.stock }}</td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="columns"></tr>
      <tr mat-row *matRowDef="let row; columns: columns"></tr>
    </table>
    <mat-paginator [pageSizeOptions]="[25, 50, 100]" aria-label="Select page of SKUs" />
  `,
})
export class Inventory implements AfterViewInit {
  readonly columns = ['sku', 'stock'];
  readonly dataSource = new MatTableDataSource<Sku>([]);
  private readonly sort = viewChild.required(MatSort);
  private readonly paginator = viewChild.required(MatPaginator);

  ngAfterViewInit() {
    this.dataSource.sort = this.sort();
    this.dataSource.paginator = this.paginator();
  }

  refresh(items: Sku[]) { this.dataSource.data = items; }
}

go deeper

for a junior

Recall the wiring: matSort on the table, mat-sort-header on headers, a mat-paginator after it, and assigning both instances to the data source once the view exists.

for a middle

Explain the filter, sort, page order, how the paginator's length is derived from filteredData, the three-step sort cycle, and why replacing the data source breaks sorting.

for a senior

Diagnose silent failures: missing module imports, too-early assignment, a paginator inside an @if, mismatched column names, and data that is really one server page.

for a principal

Decide where client-side MatTableDataSource stops being viable for a product's data volumes and when a team should standardise on a server-backed DataSource.

## What MatTableDataSource is `MatTableDataSource` is Angular Material's ready-made `DataSource` for **client-side** data: you hand it the whole array, and it decides which rows the table shows based on a filter string, a `MatSort` directive and a `MatPaginator` component. It is meant for data that fits in the browser; its own documentation points to a custom `DataSource` for server-side work. ## Wiring the pieces 1. **Imports.** Add `MatTableModule`, `MatSortModule` and `MatPaginatorModule` (or the individual classes) to the standalone component's `imports`. Without `MatSortModule`, the `matSort` and `mat-sort-header` attributes match nothing and do nothing, with no error. 2. **Template.** Put `matSort` on the `<table mat-table>` and `mat-sort-header` on each header cell that should sort. Inside a table the header's id defaults to the column name, so `matColumnDef="stock"` sorts by `stock`. Add `sortActionDescription` so the header's button tells screen-reader users it sorts. 3. **Paginator.** Place `<mat-paginator>` after the table with `pageSizeOptions` such as `[25, 50, 100]`. 4. **Assignment.** Query with `viewChild.required(MatSort)` and `viewChild.required(MatPaginator)` and assign in `ngAfterViewInit`, when the view queries have resolved. Reading the queries earlier finds nothing (a required query throws, an optional one returns `undefined`), so the data source never gets the instances and nothing sorts or pages. An initial order comes from `matSortActive="stock"` and `matSortDirection="asc"` on the `matSort` element; the data source listens for the sort's initialization, so the first render is already sorted. ## The pipeline, in order | Step | Input | What happens | |---|---|---| | Filter | `data` + `filter` | rows kept where `filterPredicate(row, filter)` is true; the result is exposed as `filteredData` | | Sort | filtered rows + `MatSort` state | a **copy** is sorted with `sortData`, which reads values through `sortingDataAccessor` | | Page | sorted rows + paginator | `slice(pageIndex * pageSize, pageIndex * pageSize + pageSize)` | Because filtering happens first, both the sort and the page count apply to the matching rows only. After each filter the data source writes the filtered count into `paginator.length`, and if the current page index is now past the last page, it moves the paginator back to the last page. It does **not** jump to the first page when the filter changes, so a common addition is `this.dataSource.paginator?.firstPage()` in the filter handler. ## Defaults worth knowing - **Sort cycle.** Clicking a header goes `asc`, then `desc`, then no sort. `matSortStart="desc"` reverses the start for all headers (or `start` on one header), and `matSortDisableClear` removes the cleared step. - **Page size.** With neither `pageSize` nor `pageSizeOptions` set, `mat-paginator` uses 50. If `pageSizeOptions` is set and `pageSize` is not, it uses the first option. The current page size is always shown in the size dropdown, even when the options list omits it. - **Events.** `matSortChange` carries `{active, direction}`; the paginator's `page` event carries a `PageEvent` with `pageIndex`, `previousPageIndex`, `pageSize` and `length`. The data source subscribes to these for you. ## Feeding new data When the inventory refreshes, set `this.dataSource.data = items`. The guide warns against building a fresh `MatTableDataSource` for every response, because the new instance has no `sort` or `paginator` attached and sorting appears to break. Keep one instance for the component's lifetime. ## Doing it without MatTableDataSource The data source is a convenience, not a requirement. You can bind a plain array and react to the components yourself: handle `(matSortChange)` on the `matSort` element and `(page)` on the paginator, compute the visible rows, and set them. If you mutate the same array instead of assigning a new one, call the table's `renderRows()`, because the table does not watch arrays. The trade-off is that you now own the filter, sort and slice logic, and the paginator's `length`, that `MatTableDataSource` would otherwise maintain. ## Failure checklist when sorting or paging does nothing - `MatSortModule` or `MatPaginatorModule` missing from `imports`. - `sort` and `paginator` assigned before the view existed, or the paginator sits inside an `@if` that was false at that moment. - The column name does not match the data property, so the default accessor reads `undefined` (a custom `sortingDataAccessor` fixes it). - A new `MatTableDataSource` created on each fetch. - The data is really a single server page, which needs a server-side `DataSource` instead.

  • A user on page 6 of an Angular Material table types a filter that leaves twelve matching SKUs; what does MatTableDataSource do to the paginator?
    It sets `paginator.length` to the filtered count and, because page 6 no longer exists, moves `pageIndex` back to the last page that does, then re-renders. It does not reset to the first page by itself, which is why filter handlers often call `paginator.firstPage()` after setting `filter`.
  • How do you make an Angular Material table open sorted by stock level, lowest first?
    Set `matSortActive="stock"` and `matSortDirection="asc"` on the `matSort` element. Once `dataSource.sort` is assigned, the data source reacts to the sort's initialization and renders the rows already in that order, and the stock header shows the active arrow.
  • Why can't the paginator be assigned to MatTableDataSource in the constructor?
    The `MatPaginator` instance is a child in the component's view, and view queries such as `viewChild` only resolve once that view is created. In the constructor the query has no result yet: a required query throws when read, and an optional one returns `undefined`, so the data source gets no paginator. `ngAfterViewInit` is the first safe point.

  • MatTableDataSource pages first, then sorts the rows on that page.
  • You can assign dataSource.sort in the constructor; it binds later.
  • Create a new MatTableDataSource for every response; it is cheap.
  • mat-paginator defaults to ten rows per page.
  • Setting filter automatically sends the paginator back to page one.
  • Clicking a sort header toggles only between ascending and descending.