Table
Import
Import TableauUiTableModule from tableau-ui-angular/table, and the data options, FullDataOptions and IncrementalDataOptions, from tableau-ui-angular/virtualize. The table measures and loads in the browser only: call load() once it is drawn.
A first table
A column is a tabColumnDef with a header and a cell template. FullDataOptions loads every row at once, sorted as the request says; click a header to sort.
import type { AfterViewInit } from '@angular/core';
import { ChangeDetectionStrategy, Component, viewChild } from '@angular/core';
import { TableauUiTableModule, TableComponent } from 'tableau-ui-angular/table';
import type { FullDataRequest } from 'tableau-ui-angular/virtualize';
import { FullDataOptions } from 'tableau-ui-angular/virtualize';
interface Person {
id: number;
name: string;
city: string;
}
const PEOPLE: Person[] = Array.from({ length: 200 }, (_, index) => ({ id: index + 1, name: `Person ${index + 1}`, city: ['Budapest', 'Seattle', 'London', 'Tokyo'][index % 4] }));
@Component({
selector: 'app-table-basic-example',
imports: [TableauUiTableModule],
templateUrl: './table-basic.example.html',
styleUrl: './table-basic.example.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TableBasicExampleComponent implements AfterViewInit {
private readonly table = viewChild.required<TableComponent<Person>>(TableComponent);
// The rows, by their key; here sorted in the browser, where a server would sort them for the request
protected readonly dataOptions = new FullDataOptions<Person>(
person => person.id,
async (request: FullDataRequest) => {
const rows = [...PEOPLE].sort((a, b) => {
for (const { property, direction } of request.sort) {
const order = String(a[property as keyof Person]).localeCompare(String(b[property as keyof Person]), undefined, { numeric: true });
if (order !== 0) {
return direction === 'asc' ? order : -order;
}
}
return 0;
});
return Promise.resolve({ data: rows });
},
);
// The table loads once it is drawn, in the browser: it measures the rows it has room for first
ngAfterViewInit(): void {
void this.table().load();
}
}Every option
Data loaded in blocks or at once, with no rows, two, or an error; columns shown, striped, pinned, resizable, sortable, with their own classes and tooltips; a template for no data; and single or multiple selection, by checkbox or by row, with a header checkbox, each row's checkbox named by rowLabel, and when a reset clears it.
import { NgTemplateOutlet } from '@angular/common';
import type { AfterViewInit } from '@angular/core';
import { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import { TableauUiButtonModule } from 'tableau-ui-angular/button';
import { TableauUiButtonToggleModule } from 'tableau-ui-angular/button-toggle';
import { TableauUiCheckboxModule } from 'tableau-ui-angular/checkbox';
import { TableauUiCommonModule } from 'tableau-ui-angular/common';
import { TableauUiExpansionPanelModule } from 'tableau-ui-angular/expansion-panel';
import type { CellContext, HeaderContext } from 'tableau-ui-angular/table';
import { MultiSelectionOptions, SingleSelectionOptions, TableauUiTableModule, TableComponent } from 'tableau-ui-angular/table';
import type { DataSort, FullDataRequest, IncrementalDataRequest } from 'tableau-ui-angular/virtualize';
import { FullDataOptions, IncrementalDataOptions } from 'tableau-ui-angular/virtualize';
interface Person {
id: number;
name: string;
age: number;
gender: string;
country: string;
city: string;
email: string;
phone: string;
address: string;
zipCode: string;
username: string;
birthdate: string;
joinDate: string;
isActive: boolean;
score: number;
role: string;
department: string;
employeeId: string;
language: string;
notes: string;
}
const pick = (values: readonly string[], id: number) => values[id % values.length];
// 10,000 made-up people, the same on every load
const PEOPLE: Person[] = Array.from({ length: 10_000 }, (_, index) => {
const id = index + 1;
return {
id,
name: `User ${id}`,
age: 18 + ((id * 7) % 60),
gender: pick(['Female', 'Male', 'Other'], id),
country: pick(['Japan', 'Brazil', 'France', 'Canada', 'India'], id),
city: `City ${id % 97}`,
email: `user${id}@mail.com`,
phone: `+1-555-${String(id).padStart(6, '0')}`,
address: `${(id * 13) % 999} High St`,
zipCode: String(10000 + ((id * 37) % 89999)),
username: `user${id}`,
birthdate: `${1950 + (id % 50)}-0${1 + (id % 9)}-1${id % 10}`,
joinDate: `${2010 + (id % 15)}-0${1 + (id % 9)}-2${id % 8}`,
isActive: id % 4 !== 0,
score: (id * 13) % 100,
role: pick(['Analyst', 'Manager', 'Director', 'Engineer'], id),
department: `Dept ${id % 12}`,
employeeId: `EMP${1000 + id}`,
language: pick(['English', 'Spanish', 'Japanese', 'French'], id),
notes: `Note ${id}`,
};
});
@Component({
selector: 'app-table-options-example',
imports: [NgTemplateOutlet, TableauUiButtonModule, TableauUiButtonToggleModule, TableauUiCheckboxModule, TableauUiCommonModule, TableauUiExpansionPanelModule, TableauUiTableModule],
templateUrl: './table-options.example.html',
styleUrl: './table-options.example.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TableOptionsExampleComponent implements AfterViewInit {
// #region Data
readonly $dataMode = signal<'incremental' | 'full'>('incremental');
readonly $showData = signal(true);
readonly $errorOnData = signal(false);
readonly $showTop2Data = signal(false);
// A server answering after a second, with the rows sorted as the table asks
private async request(abort: AbortSignal, dataSort: readonly DataSort[]): Promise<Person[]> {
await new Promise(resolve => setTimeout(resolve, 1000));
if (abort.aborted) {
throw new Error('Data load aborted');
}
if (!this.$showData()) {
return [];
}
const rows = this.$showTop2Data() ? PEOPLE.slice(0, 2) : [...PEOPLE];
return rows.sort((a, b) => {
for (const sort of dataSort) {
const aValue = (a as unknown as Record<string, boolean | number | string>)[sort.property];
const bValue = (b as unknown as Record<string, boolean | number | string>)[sort.property];
if (aValue < bValue) return sort.direction === 'asc' ? -1 : 1;
if (aValue > bValue) return sort.direction === 'asc' ? 1 : -1;
}
return 0;
});
}
// Incremental loads a block at a time as the user scrolls; full loads every row at once. Both draw only the rows that show
readonly $dataOptions = computed(() => {
switch (this.$dataMode()) {
case 'incremental':
return new IncrementalDataOptions<Person>(
row => row.id,
async (req: IncrementalDataRequest) => {
const rows = await this.request(req.abort, req.sort);
if (this.$errorOnData() && req.offset > 20) {
throw new Error('Simulated error on data load');
}
return { total: rows.length, data: rows.slice(req.offset, req.offset + req.count) };
},
);
case 'full':
return new FullDataOptions<Person>(
row => row.id,
async (req: FullDataRequest) => {
const rows = await this.request(req.abort, req.sort);
if (this.$errorOnData()) {
throw new Error('Simulated error on data load');
}
return { data: rows };
},
);
}
throw new Error('Unknown data mode');
});
private readonly tabTable = viewChild.required<TableComponent<Person>>(TableComponent);
ngAfterViewInit(): void {
void this.tabTable().load();
}
reset(showData: boolean, errorOnData: boolean, top2Data: boolean) {
this.$showData.set(showData);
this.$errorOnData.set(errorOnData);
this.$showTop2Data.set(top2Data);
void this.tabTable().reset();
}
// #endregion
// #region Columns
readonly $show_first_3_columns = signal(false);
readonly $striped = signal(false);
readonly $customNoDataTemplate = signal(false);
readonly $pinColumns = signal(false);
readonly $pinnedLeftColumn = computed(() => (this.$pinColumns() ? 'id' : undefined));
readonly $pinnedRightColumn = computed(() => (this.$pinColumns() ? 'age' : undefined));
// A header's class from its column's context
customCalculatedClass(ctx: HeaderContext<Person>): string | undefined {
return `custom-dynamic-class-${ctx.meta.index % 3}`;
}
// The cell tooltip shows on odd rows only
$showCellTooltip(cellContext: CellContext<Person>) {
return cellContext.meta.odd;
}
// #endregion
// #region Selection
readonly $selectionMode = signal<'single' | 'multi' | 'none'>('none');
readonly $clearSelectionOnManualReset = signal(true);
readonly $clearSelectionOnAnyReset = signal(false);
readonly $allowRowSelection = signal(false);
readonly $multiSelectHeaderCheckboxMode = signal<'none' | 'selectNone' | 'selectAll'>('none');
readonly $selectionOptions = computed(() => {
const mode = this.$allowRowSelection() ? 'row-and-checkbox' : 'checkbox';
switch (this.$selectionMode()) {
case 'none':
return undefined;
case 'single':
return new SingleSelectionOptions(mode, this.$clearSelectionOnManualReset(), this.$clearSelectionOnAnyReset());
case 'multi':
return new MultiSelectionOptions(this.$multiSelectHeaderCheckboxMode(), mode, this.$clearSelectionOnManualReset(), this.$clearSelectionOnAnyReset());
}
return undefined;
});
readonly $selectedRows = signal<Map<number, Person>>(new Map<number, Person>());
// Names each row's checkbox for screen readers: "Select User 12"
readonly personName = (person: Person) => person.name;
// #endregion
}Accessibility
The table scrolls in its own host, which is in the Tab order, so the keyboard scrolls it in every browser, even when nothing in its rows takes focus.
- A table that scrolls needs
label, which names it for screen readers: its host is then a region of that name, and its table too. A staticaria-labelontab-tablenames it the same way, andlabelwins. Without a name the host has no role. - A static
tabindex="-1"ontab-tabletakes it out of the Tab order, as for a short table whose cells hold controls of their own. Atabindexan app put on a wrapper so the keyboard could scroll the table can go. - Once the host has focus, the arrow keys, Page Up, Page Down, Home and End scroll it, and the rows they reach load.
- A row whose block failed shows a red bar in each cell, which a screen reader reads as "Failed to load".
- A static
rolethe app writes ontab-tablestays. - The header row and each data row are rows, the data rows in a row group. The table says how many rows it has, the header row included, and each row its place in the whole data, so a screen reader says which row it is on though only the rows near the view are drawn. Until a load says the total, the count is unknown. "No data available" is a row with one cell across the columns.
- Enter, Space or a click on a sortable header sorts by its column, and focus stays on its button, whose tooltip shows the new sort. With
sortMode="multi", Shift+Enter, Shift+Space or Shift+Click adds the column to the sort. The first sort's column header says its direction (aria-sort); a later sort's button says its place, "sort 2, descending". - With selection on, each row's checkbox is named "Select" and the name
rowLabelgives the row, such as "Select User 12", or its place without one, "Select row 12". The header's checkbox is named "Select all rows" or "Clear the selection", and the column "Selection". Each loaded row says whether it is selected (aria-selected). - A resizable column's edge is a separator in the Tab order, after its header's button, named "Resize" and the header's text, such as "Resize Name". A screen reader hears the column's width in pixels, and its minimum and maximum. Right and Left widen and narrow the column by 10 pixels, 50 with Shift; Home and End take it to its minimum and maximum width, or without a maximum to the table's visible width. A mouse, a finger or a pen drags it. Every column resizes unless it sets
[resizable]="false", which also keeps it out of the Tab order. - Each column header is named by its text alone, so a cell's column is read without its sort's place or its resizer's name. A header needs words: give an icon alone a
label, or hidden text. A header without words is named by its place, "Column 3", and so are its button and its resizer.