Why do Angular Material's default `MatTableDataSource` filtering and sorting fail on nested or computed fields, and how do `filterPredicate` and `sortingDataAccessor` fix it?
answer
- the defaults only see top-level values
- objects stringify to [object Object]
- row[columnName] is the sort key
- string comparison is case-sensitive
- matNoDataRow for zero matches
basics
~20 sThe default filterPredicate stringifies each top-level value, so a nested object becomes [object Object], and the default sortingDataAccessor reads row[columnName], which is undefined for computed columns. Replace them with functions that return the exact text to match and the value to sort by.
solid answer
~40 s`MatTableDataSource`'s default `filterPredicate` trims and lower-cases the filter, then checks whether any top-level value of the row, turned into a string, contains it. A nested object turns into `[object Object]`, so its fields are unsearchable and a filter such as `obj` matches every row that has one. The default `sortingDataAccessor` returns `row[sortHeaderId]`, converting numeric strings to numbers, so a column named `available` that shows `onHand - reserved` sorts by `undefined` and nothing moves, and text compares by character code, so capitals sort before lowercase. Assign your own functions: a `filterPredicate(row, filter)` that matches the fields you choose, and a `sortingDataAccessor(row, column)` that returns a number or a normalised string per column. Add a `*matNoDataRow` template to say when nothing matches.
code
ts · 28 linesimport {MatTableDataSource} from '@angular/material/table';
interface InventoryRow {
sku: string;
name: string;
stock: {onHand: number; reserved: number};
location: {aisle: string; bin: number};
}
export function createInventorySource(rows: InventoryRow[]) {
const source = new MatTableDataSource<InventoryRow>(rows);
source.filterPredicate = (row, filter) => {
const term = filter.trim().toLowerCase();
return [row.sku, row.name, `${row.location.aisle}-${row.location.bin}`]
.some(field => field.toLowerCase().includes(term));
};
source.sortingDataAccessor = (row, column) => {
switch (column) {
case 'available': return row.stock.onHand - row.stock.reserved;
case 'bin': return row.location.bin;
case 'name': return row.name.toLowerCase();
default: return row.sku;
}
};
return source;
}go deeper
Recall that MatTableDataSource filters with a filter string and sorts by the property that matches the column name, and that both behaviours can be replaced.
Explain the stringify-top-level-values filter, the row[columnName] accessor with numeric-string conversion, case-sensitive comparison, and how matNoDataRow appears for empty results.
Write predicates and accessors that are cheap per row, search exactly the intended fields, handle structured filters, and spot [object Object] false positives in a bug report.
Set a team convention for column naming, searchable fields and locale-aware sorting so tables behave the same across screens, and know when client-side filtering should move to the server.
## What the defaults actually do `MatTableDataSource` exposes two replaceable functions, and both are plain properties you can assign. | Function | Default behaviour | Breaks when | |---|---|---| | `filterPredicate(data, filter)` | trims and lower-cases `filter`; returns true if any **top-level** value, stringified and lower-cased, contains it | a value is a nested object, a date, or a field you never want searched | | `sortingDataAccessor(data, sortHeaderId)` | returns `data[sortHeaderId]`; numeric strings become numbers (unless they exceed `Number.MAX_SAFE_INTEGER`) | the column name is not a property, the value is nested, or text needs case-insensitive order | The default sort (`sortData`) compares the two accessor results with `>` and `<`. If one side is a number and the other a string, both are compared as strings. `null` and `undefined` values sort before present values in ascending order. ## The warehouse rows that break them Take inventory rows shaped like `{sku: 'BX-1042', name: 'bracket', stock: {onHand: 7, reserved: 2}, location: {aisle: 'C', bin: 14}}`, with displayed columns `sku`, `name`, `available` (shown as `onHand - reserved`) and `bin`. - **Filtering by bin.** Typing `14` never finds the row through `location`, because `location` stringifies to `[object Object]`. - **False positives.** Typing `obj`, or any substring of `[object object]`, matches every row that has a nested object. - **Sorting `available`.** `data['available']` is `undefined` on every row, so every comparison ties and the order does not change. - **Sorting `name`.** `'Bolt'` sorts before `'anchor'`, because uppercase letters have lower character codes than lowercase ones. - **Sorting `bin`.** The header id `bin` is not a property either; the value lives at `location.bin`. ## Replacing the accessor Write one function that switches on the column id and returns the value to compare: ```ts this.dataSource.sortingDataAccessor = (row, column) => { switch (column) { case 'available': return row.stock.onHand - row.stock.reserved; case 'bin': return row.location.bin; case 'name': return row.name.toLocaleLowerCase(); default: return (row as any)[column]; } }; ``` Return numbers for numeric columns so `9` sorts before `10`, and a normalised string for text. If you need full locale-aware collation, you can replace `sortData` itself, which receives the whole array and the `MatSort` state. ## Replacing the predicate The predicate receives the row and the current filter string and returns a boolean. Two common shapes: 1. **Choose the searchable fields.** Build a string from `sku`, `name` and `location.bin` and test `includes(filter.trim().toLowerCase())`. Internal ids and timestamps stop producing surprise matches. 2. **Structured filters.** `filter` is typed as a string, so a screen with separate SKU-prefix and minimum-stock inputs serialises an object with `JSON.stringify` into `filter` and parses it inside the predicate. The predicate runs once per row on every filter or data change, so keep it cheap. Assign it before the first filter is set: changing `filterPredicate` alone does not re-run filtering until `filter` or `data` changes. ## Showing an empty result Add a no-data row inside the table: ```html <tr *matNoDataRow> <td [attr.colspan]="columns.length">No SKUs match "{{ query() }}"</td> </tr> ``` The table renders this template whenever it has no data rows to show, whether because the filter excluded everything or the data is empty, and removes it when rows return. `filteredData` holds the matching rows, which is what a "select all" action should use rather than `data`. ## Numbers hiding in strings The default accessor converts numeric strings to numbers before comparing, which helps a `stock` field that arrives as `"12"` from a CSV import. It can surprise you elsewhere: SKU codes such as `"0042"` and `"42"` both become `42` and tie, and a code made only of digits sorts numerically while mixed codes like `"BX-1042"` stay strings, and any comparison between a converted number and a string falls back to comparing both as strings. Values beyond `Number.MAX_SAFE_INTEGER` stay strings because they cannot be compared reliably as numbers. Return the raw string from your accessor when a code must sort as text. ## Checklist - Keep column names equal to property names where you can; it lets the default accessor work. - Override `sortingDataAccessor` for computed, nested or case-sensitive columns. - Override `filterPredicate` to choose fields and to search nested values. - Provide `*matNoDataRow` with a `colspan` that spans the displayed columns.
- An Angular Material inventory screen has separate SKU-prefix and minimum-stock inputs; how do you feed both to one MatTableDataSource?`filter` is a string, so serialise both values with `JSON.stringify({prefix, minStock})` and assign the result to `dataSource.filter`. The custom `filterPredicate` parses it and applies both conditions. Setting the string re-runs filtering, and the paginator length follows the matching count.
- After you assign a new filterPredicate to a MatTableDataSource that already has a filter, why does the table still show the old matches?`filterPredicate` is a plain property; assigning it does not trigger the data source's pipeline. Filtering re-runs when `filter` or `data` changes. Assign the predicate when you create the data source, or re-assign `filter` after changing it.
- When does an Angular Material table show its matNoDataRow template?Whenever the table has no data rows rendered: a filter that excludes everything, an empty array, or an empty server page. It is removed as soon as rows come back. Give its cell a `colspan` equal to the number of displayed columns so the message spans the table.
- The default filter searches nested objects field by field.
- The default accessor sorts by the text rendered in each cell.
- Default text sorting in MatTableDataSource ignores letter case.
- Computed columns sort correctly as long as mat-sort-header is present.
- Changing filterPredicate immediately re-filters the rows on screen.
- matNoDataRow appears only when a filter is set.