Tableau UI for Angular
Dashboard
A Tableau-style sales dashboard of the library's components, which moves its table's columns with the Angular CDK, and its source.
- Its frame is the enhanced table, below: a header row with an Actions menu, the selection button, a product search, Filters with the number in use, and Layout & Sorting, which open a drawer.
- The filters: a multi select, a single select, a button toggle, two date pickers, a customer search with suggestions and two checkboxes. Each filter in use shows as a chip, which clears it.
- The KPIs, the charts, the orders and the products follow the filters and the search. A KPI's tooltip says how it is counted.
- The Orders tab holds 3,000 orders, made in the code, in the virtual table: a header sorts them, the checkboxes select them, each named by its order, such as "Select order 1042", and the button by an order's number opens its details in a dialog. The Products tab has a panel per category.
- The selection button's menu copies the selected orders to the clipboard or clears the selection; the Actions menu copies every order the filters keep, or resets the filters. A copy and a reset say so in a snack.
- The charts are SVG in the template, since the library has no charts; the page adds no chart library.
- On a narrow dashboard, the drawer covers it while it shows.
Garden shop sales, 2025
3,000 of 3,000 ordersSales$243,155100% of the year's sales
Profit$69,45528.6% margin
Orders3,0007,560 items
Average order$8148 customers
$50K$25K
Monthly average $20.3K
Filters
All regions
All categories
All
Online
In store
import { CurrencyPipe, DatePipe, PercentPipe } from '@angular/common';
import type { TemplateRef } from '@angular/core';
import { afterNextRender, ChangeDetectionStrategy, Component, computed, ElementRef, inject, Injector, linkedSignal, signal, viewChild } from '@angular/core';
import { TableauUiAutoCompleteModule } from 'tableau-ui-angular/autocomplete';
import { TableauUiButtonModule } from 'tableau-ui-angular/button';
import { TableauUiButtonToggleModule } from 'tableau-ui-angular/button-toggle';
import { TableauUiCheckboxModule } from 'tableau-ui-angular/checkbox';
import { TableauUiChipModule } from 'tableau-ui-angular/chip';
import { ClipboardService } from 'tableau-ui-angular/clipboard';
import { TableauUiCommonModule } from 'tableau-ui-angular/common';
import { TableauUiDatePickerModule } from 'tableau-ui-angular/date-picker';
import { DialogService } from 'tableau-ui-angular/dialog';
import { TableauUiExpansionPanelModule } from 'tableau-ui-angular/expansion-panel';
import { TableauUiFormFieldModule } from 'tableau-ui-angular/form-field';
import { TableauUiIconModule } from 'tableau-ui-angular/icon';
import { TableauUiMenuModule } from 'tableau-ui-angular/menu';
import { TableauUiMenuButtonModule } from 'tableau-ui-angular/menu-button';
import { TableauUiSelectModule } from 'tableau-ui-angular/select';
import { SnackService } from 'tableau-ui-angular/snack';
import { TableauUiTabgroupModule, TabGroupComponent } from 'tableau-ui-angular/tab-group';
import { ThemeService } from 'tableau-ui-angular/theme';
import type { TableComponent } from 'tableau-ui-angular/table';
import { MultiSelectionOptions, TableauUiTableModule } from 'tableau-ui-angular/table';
import { TableauUiTooltipModule } from 'tableau-ui-angular/tooltip';
import type { DataSort, FullDataRequest } from 'tableau-ui-angular/virtualize';
import { FullDataOptions } from 'tableau-ui-angular/virtualize';
import { EnhancedTableComponent, FilterPanelDirective, HeaderBeforeSelectDirective, SelectMenuButtonsDirective } from './enhanced-table.component';
type Region = 'Central' | 'East' | 'North' | 'South' | 'West';
type Category = 'Plants' | 'Pots' | 'Seeds' | 'Tools';
type Channel = 'In store' | 'Online';
type Filter = 'category' | 'channel' | 'customer' | 'discounted' | 'from' | 'regions' | 'returns' | 'search' | 'to';
interface Order {
id: number;
date: Date;
customer: string;
region: Region;
channel: Channel;
product: string;
category: Category;
quantity: number;
// 0, 0.1, 0.2 or 0.3 off the price
discount: number;
// what the customer paid, and that less what the goods cost
sales: number;
profit: number;
returned: boolean;
}
const REGIONS: readonly Region[] = ['North', 'South', 'East', 'West', 'Central'];
const CATEGORIES: readonly Category[] = ['Plants', 'Pots', 'Tools', 'Seeds'];
// the share of a price the shop keeps before any discount
const MARGINS: Record<Category, number> = { Plants: 0.45, Pots: 0.3, Tools: 0.22, Seeds: 0.6 };
const PRODUCTS: readonly { name: string; category: Category; price: number }[] = [
{ name: 'Monstera', category: 'Plants', price: 34 },
{ name: 'Fiddle-leaf fig', category: 'Plants', price: 48 },
{ name: 'Snake plant', category: 'Plants', price: 22 },
{ name: 'Boston fern', category: 'Plants', price: 18 },
{ name: 'Olive tree', category: 'Plants', price: 89 },
{ name: 'Lavender', category: 'Plants', price: 9 },
{ name: 'Terracotta pot', category: 'Pots', price: 12 },
{ name: 'Glazed planter', category: 'Pots', price: 39 },
{ name: 'Hanging basket', category: 'Pots', price: 24 },
{ name: 'Raised bed', category: 'Pots', price: 129 },
{ name: 'Pruning shears', category: 'Tools', price: 29 },
{ name: 'Hand trowel', category: 'Tools', price: 14 },
{ name: 'Watering can', category: 'Tools', price: 26 },
{ name: 'Garden hose', category: 'Tools', price: 45 },
{ name: 'Wheelbarrow', category: 'Tools', price: 119 },
{ name: 'Tomato seeds', category: 'Seeds', price: 4 },
{ name: 'Basil seeds', category: 'Seeds', price: 3 },
{ name: 'Sunflower seeds', category: 'Seeds', price: 4 },
{ name: 'Wildflower mix', category: 'Seeds', price: 7 },
{ name: 'Lawn seed', category: 'Seeds', price: 24 },
];
const FIRST_NAMES = ['Ada', 'Ben', 'Carla', 'Dev', 'Ema', 'Finn', 'Gia', 'Hugo', 'Ines', 'Jon', 'Kira', 'Leo'];
const LAST_NAMES = ['Park', 'Okafor', 'Diaz', 'Novak', 'Walsh', 'Lind', 'Silva', 'Berg'];
// 48 customers, each name once
const CUSTOMERS = Array.from({ length: 48 }, (_, index) => `${FIRST_NAMES[index % 12]} ${LAST_NAMES[(index * 5 + Math.floor(index / 12)) % 8]}`);
// a garden shop's year: each month's share of the orders
const SEASON = [3, 4, 7, 11, 13, 10, 8, 7, 6, 5, 4, 6];
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// 3,000 made-up orders in 2025, the same on every load: a seeded random number generator picks each value
function makeOrders(count: number): Order[] {
let seed = 2025;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
const pick = <T>(values: readonly T[]) => values[Math.floor(random() * values.length)];
const months = SEASON.flatMap((weight, month) => Array.from({ length: weight }, () => month));
const cents = (value: number) => Math.round(value * 100) / 100;
const orders = Array.from({ length: count }, (): Order => {
const month = pick(months);
const product = pick(PRODUCTS);
const quantity = 1 + Math.floor(random() * 4);
const discount = pick([0, 0, 0, 0, 0, 0.1, 0.1, 0.2, 0.3]);
const sales = cents(product.price * quantity * (1 - discount));
return {
id: 0,
date: new Date(2025, month, 1 + Math.floor(random() * new Date(2025, month + 1, 0).getDate())),
customer: pick(CUSTOMERS),
region: pick<Region>(['North', 'North', 'South', 'East', 'East', 'East', 'West', 'West', 'Central']),
channel: pick<Channel>(['Online', 'Online', 'Online', 'In store', 'In store']),
product: product.name,
category: product.category,
quantity,
discount,
sales,
profit: cents(sales - product.price * quantity * (1 - MARGINS[product.category])),
returned: random() < 0.04,
};
});
// numbered in the order they came in
return orders.sort((a, b) => a.date.getTime() - b.date.getTime()).map((order, index) => ({ ...order, id: 10001 + index }));
}
const ORDERS = makeOrders(3000);
const sum = <T>(rows: readonly T[], value: (row: T) => number) => rows.reduce((total, row) => total + value(row), 0);
const MONEY = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
const SHORT_MONEY = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', notation: 'compact', maximumFractionDigits: 1 });
const PERCENT = new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 1 });
const COUNT = new Intl.NumberFormat('en-US');
// A count and its noun: 1 order, 1,652 orders
const plural = (count: number, noun: string) => `${COUNT.format(count)} ${count === 1 ? noun : `${noun}s`}`;
const DAY = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
// A day as YYYY-MM-DD, in local time as the orders' dates are
const isoDay = (date: Date) => [date.getFullYear(), date.getMonth() + 1, date.getDate()].map(part => String(part).padStart(2, '0')).join('-');
const TOTAL_SALES = sum(ORDERS, order => order.sales);
// The smallest of 1, 2, 2.5 and 5 times a power of 10 at or above the value: a chart's top line
function niceCeiling(value: number) {
const step = 10 ** Math.floor(Math.log10(value));
return [1, 2, 2.5, 5, 10].map(factor => factor * step).find(top => top >= value) ?? value;
}
// A sparkline in a 110 by 30 box, a month every 10: its line, and a dot for a month with gaps on both sides, which a
// line can't draw; a month with no value is a gap
function sparkline(values: (number | undefined)[]) {
const known = values.filter(value => value !== undefined);
const [low, high] = [Math.min(...known), Math.max(...known)];
const point = (value: number, index: number) => `${index * 10},${28 - ((value - low) / (high - low || 1)) * 26}`;
const alone = (index: number) => values[index - 1] === undefined && values[index + 1] === undefined;
return {
line: values
.map((value, index) => (value === undefined || alone(index) ? '' : `${index === 0 || values[index - 1] === undefined ? 'M' : 'L'}${point(value, index)}`))
.filter(part => part !== '')
.join(' '),
// a line of no length, which round caps draw as a dot
dots: values
.map((value, index) => (value !== undefined && alone(index) ? `M${point(value, index)} h0.01` : ''))
.filter(part => part !== '')
.join(' '),
};
}
// What a sparkline shows, for a screen reader
function monthByMonth(label: string, values: (number | undefined)[], format: (value: number) => string) {
return `${label} by month: ${values.map((value, index) => `${MONTHS[index]} ${value === undefined ? 'no orders' : format(value)}`).join(', ')}`;
}
// Sorted in the browser, as the table asks; a server would sort them for the request
function sortOrders(orders: readonly Order[], sort: readonly DataSort[]) {
return [...orders].sort((a, b) => {
for (const { property, direction } of sort) {
const [x, y] = [a[property as keyof Order], b[property as keyof Order]];
const order = typeof x === 'string' && typeof y === 'string' ? x.localeCompare(y) : Number(x) - Number(y);
if (order !== 0) {
return direction === 'asc' ? order : -order;
}
}
return 0;
});
}
@Component({
selector: 'app-sales-dashboard-example',
imports: [
CurrencyPipe,
DatePipe,
PercentPipe,
TableauUiAutoCompleteModule,
TableauUiButtonModule,
TableauUiButtonToggleModule,
TableauUiCheckboxModule,
TableauUiChipModule,
TableauUiCommonModule,
TableauUiDatePickerModule,
TableauUiExpansionPanelModule,
TableauUiFormFieldModule,
TableauUiIconModule,
TableauUiMenuModule,
TableauUiMenuButtonModule,
TableauUiSelectModule,
TableauUiTabgroupModule,
TableauUiTableModule,
TableauUiTooltipModule,
EnhancedTableComponent,
FilterPanelDirective,
HeaderBeforeSelectDirective,
SelectMenuButtonsDirective,
],
templateUrl: './sales-dashboard.example.html',
styleUrl: './sales-dashboard.example.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SalesDashboardExampleComponent {
private readonly clipboard = inject(ClipboardService);
private readonly dialogs = inject(DialogService);
private readonly snacks = inject(SnackService);
private readonly theme = inject(ThemeService);
// The charts' marks take a brighter blue on dark
protected readonly $dark = computed(() => this.theme.$appliedThemeMode() === 'dark');
private readonly table = viewChild.required<TableComponent<Order>>('table');
private readonly details = viewChild.required<TemplateRef<{ $implicit: Order }>>('details');
private readonly tabs = viewChild.required(TabGroupComponent);
private readonly frame = viewChild.required<EnhancedTableComponent<Order>>(EnhancedTableComponent);
private readonly actionsButton = viewChild<unknown, ElementRef<HTMLElement>>('actionsButton', { read: ElementRef });
private readonly injector = inject(Injector);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
protected readonly regions = REGIONS;
protected readonly categories = CATEGORIES;
protected readonly orderCount = COUNT.format(ORDERS.length);
// #region Filters
// Each filter's value; none set keeps every order
protected readonly $regions = signal<Region[] | undefined>(undefined);
protected readonly $category = signal<Category | undefined>(undefined);
protected readonly $channel = signal<Channel | 'All' | undefined>('All');
protected readonly $from = signal<Date | undefined>(undefined);
protected readonly $to = signal<Date | undefined>(undefined);
protected readonly $customer = signal('');
protected readonly $discountedOnly = signal(false);
protected readonly $withReturns = signal(true);
// The search, in the table's header row, looks in the products' names
protected readonly $search = signal('');
protected readonly $suggestions = computed(() => {
const text = this.$customer().trim().toLowerCase();
return CUSTOMERS.filter(name => name.toLowerCase().includes(text)).slice(0, 8);
});
// The orders the filters keep: everything below follows them
protected readonly $orders = computed(() => {
const regions = this.$regions() ?? [];
const category = this.$category();
const channel = this.$channel() ?? 'All';
const from = this.$from()?.getTime() ?? -Infinity;
const to = this.$to()?.getTime() ?? Infinity;
const customer = this.$customer().trim().toLowerCase();
const search = this.$search().trim().toLowerCase();
const discountedOnly = this.$discountedOnly();
const withReturns = this.$withReturns();
return ORDERS.filter(
order =>
(regions.length === 0 || regions.includes(order.region)) &&
(category === undefined || order.category === category) &&
(channel === 'All' || order.channel === channel) &&
order.date.getTime() >= from &&
order.date.getTime() <= to &&
order.customer.toLowerCase().includes(customer) &&
order.product.toLowerCase().includes(search) &&
(!discountedOnly || order.discount > 0) &&
(withReturns || !order.returned),
);
});
protected readonly $count = computed(() => COUNT.format(this.$orders().length));
// The filters that keep fewer orders, each a chip that clears it
protected readonly $chips = computed(() => {
const chips: { key: Filter; text: string }[] = [];
const regions = this.$regions() ?? [];
const [category, channel, from, to, customer, search] = [this.$category(), this.$channel(), this.$from(), this.$to(), this.$customer().trim(), this.$search().trim()];
if (regions.length > 0) chips.push({ key: 'regions', text: `Region: ${regions.join(', ')}` });
if (category) chips.push({ key: 'category', text: `Category: ${category}` });
if (channel !== 'All' && channel !== undefined) chips.push({ key: 'channel', text: `Channel: ${channel}` });
if (from) chips.push({ key: 'from', text: `From ${DAY.format(from)}` });
if (to) chips.push({ key: 'to', text: `To ${DAY.format(to)}` });
if (customer) chips.push({ key: 'customer', text: `Customer: ${customer}` });
if (search) chips.push({ key: 'search', text: `Search: ${search}` });
if (this.$discountedOnly()) chips.push({ key: 'discounted', text: 'Discounted only' });
if (!this.$withReturns()) chips.push({ key: 'returns', text: 'No returns' });
return chips;
});
// The Filters button counts the filters in its panel: the search shows in its own field
protected readonly $filterCount = computed(() => this.$chips().filter(chip => chip.key !== 'search').length);
protected customerInput(event: Event) {
this.$customer.set((event.target as HTMLInputElement).value);
}
protected clearFilter(key: Filter) {
switch (key) {
case 'regions':
this.$regions.set(undefined);
break;
case 'category':
this.$category.set(undefined);
break;
case 'channel':
this.$channel.set('All');
break;
case 'from':
this.$from.set(undefined);
break;
case 'to':
this.$to.set(undefined);
break;
case 'customer':
this.$customer.set('');
break;
case 'search':
this.$search.set('');
break;
case 'discounted':
this.$discountedOnly.set(false);
break;
case 'returns':
this.$withReturns.set(true);
break;
}
}
// A chip's remove button goes with it, so focus goes to the next chip's, else the one before, else the Filters button
protected removeChip(key: Filter, index: number) {
this.clearFilter(key);
afterNextRender(
() => {
const buttons = Array.from(this.host.querySelectorAll<HTMLElement>('.chips button'));
const next = buttons.at(index) ?? (index > 0 ? buttons.at(index - 1) : undefined);
if (next !== undefined) {
next.focus();
} else {
this.frame().focusToggle('filter');
}
},
{ injector: this.injector },
);
}
// Clear all filters, in the panel, leaves the search; Reset the filters, in the Actions menu, clears it too
protected clearFilters() {
for (const { key } of this.$chips().filter(chip => chip.key !== 'search')) {
this.clearFilter(key);
}
}
protected resetFilters() {
for (const { key } of this.$chips()) {
this.clearFilter(key);
}
this.snacks.openSnack(`Filters reset: all ${this.orderCount} orders`, 3000, 'info');
}
// The layout is the Orders table's, so its tab shows when the layout panel opens
protected drawerOpened(panel: 'filter' | 'layout') {
if (panel === 'layout') {
this.tabs().selectTabByKey('orders');
}
}
// #endregion
// #region KPIs and charts
private readonly $months = computed(() => {
const months = MONTHS.map(() => ({ sales: 0, profit: 0, orders: 0 }));
for (const order of this.$orders()) {
const month = months[order.date.getMonth()];
month.sales += order.sales;
month.profit += order.profit;
month.orders++;
}
return months;
});
protected readonly $kpis = computed(() => {
const [orders, months] = [this.$orders(), this.$months()];
const sales = sum(orders, order => order.sales);
const profit = sum(orders, order => order.profit);
// a month with no orders has no average order, rather than one of $0
const averages = months.map(month => (month.orders === 0 ? undefined : month.sales / month.orders));
const tile = (label: string, value: string, note: string, about: string, series: (number | undefined)[], format: (value: number) => string, loss = false) => ({
label,
value,
note,
about,
...sparkline(series),
description: monthByMonth(label, series, format),
loss,
});
return [
tile(
'Sales',
MONEY.format(sales),
`${PERCENT.format(sales / TOTAL_SALES)} of the year's sales`,
'What customers paid, after discounts',
months.map(month => month.sales),
value => MONEY.format(value),
),
tile(
'Profit',
MONEY.format(profit),
`${PERCENT.format(sales === 0 ? 0 : profit / sales)} margin`,
'Sales less what the goods cost; a deep discount sells at a loss',
months.map(month => month.profit),
value => MONEY.format(value),
profit < 0,
),
tile(
'Orders',
COUNT.format(orders.length),
plural(
sum(orders, order => order.quantity),
'item',
),
'Each order is one product, in any quantity',
months.map(month => month.orders),
value => COUNT.format(value),
),
tile(
'Average order',
MONEY.format(orders.length === 0 ? 0 : sales / orders.length),
plural(new Set(orders.map(order => order.customer)).size, 'customer'),
'Sales divided by orders',
averages,
value => MONEY.format(value),
),
];
});
// The months the date filters cover, of which the monthly average is the mean
private readonly $coveredMonths = computed(() => {
const [from, to] = [this.$from()?.getTime() ?? -Infinity, this.$to()?.getTime() ?? Infinity];
return MONTHS.filter((_, month) => new Date(2025, month + 1, 0).getTime() >= from && new Date(2025, month, 1).getTime() <= to).length;
});
// Columns in a 120 by 100 box, a month every 10, under the top line; the monthly average as a reference line
protected readonly $monthChart = computed(() => {
const months = this.$months();
const top = niceCeiling(Math.max(...months.map(month => month.sales), 1));
const average = sum(months, month => month.sales) / Math.max(this.$coveredMonths(), 1);
return {
top: SHORT_MONEY.format(top),
half: SHORT_MONEY.format(top / 2),
columns: months.map((month, index) => ({ label: MONTHS[index], x: index * 10 + 2, height: (month.sales / top) * 100 })),
average: (average / top) * 100,
averageText: `Monthly average ${SHORT_MONEY.format(average)}`,
description: `Sales by month: ${months.map((month, index) => `${MONTHS[index]} ${MONEY.format(month.sales)}`).join(', ')}`,
};
});
protected readonly $regionBars = computed(() => {
const totals = REGIONS.map(region => ({
region,
sales: sum(
this.$orders().filter(order => order.region === region),
order => order.sales,
),
}));
const top = Math.max(...totals.map(total => total.sales), 1);
return totals
.filter(total => total.sales > 0)
.sort((a, b) => b.sales - a.sales)
.map(total => ({ label: total.region, width: (total.sales / top) * 100, value: SHORT_MONEY.format(total.sales) }));
});
// A loss's bar runs as far as a profit's would, in the error colour
protected readonly $categoryBars = computed(() => {
const totals = CATEGORIES.map(category => ({
category,
profit: sum(
this.$orders().filter(order => order.category === category),
order => order.profit,
),
}));
const top = Math.max(...totals.map(total => Math.abs(total.profit)), 1);
return totals.map(total => ({ label: total.category, width: (Math.abs(total.profit) / top) * 100, value: SHORT_MONEY.format(total.profit), loss: total.profit < 0 }));
});
// Each category's products by sales, their bars on one scale
protected readonly $productGroups = computed(() => {
const totals = new Map(PRODUCTS.map(product => [product.name, { units: 0, sales: 0 }]));
for (const order of this.$orders()) {
const total = totals.get(order.product)!;
total.units += order.quantity;
total.sales += order.sales;
}
const top = Math.max(...[...totals.values()].map(total => total.sales), 1);
return CATEGORIES.map(category => {
const products = PRODUCTS.filter(product => product.category === category)
.map(product => ({ name: product.name, ...totals.get(product.name)! }))
.sort((a, b) => b.sales - a.sales);
return {
category,
sales: MONEY.format(sum(products, product => product.sales)),
products: products.map(product => ({ label: product.name, units: COUNT.format(product.units), width: (product.sales / top) * 100, value: MONEY.format(product.sales) })),
};
});
});
// #endregion
// #region Orders
// A new load each time the filters change; the table loads it, sorted as its headers say
protected readonly $sort = signal<DataSort[]>([{ property: 'date', direction: 'desc' }]);
protected readonly $dataOptions = computed(() => {
const orders = this.$orders();
return new FullDataOptions<Order>(
order => order.id,
async (request: FullDataRequest) => Promise.resolve({ data: sortOrders(orders, request.sort) }),
);
});
protected readonly selectionOptions = new MultiSelectionOptions('selectAll', 'checkbox', true, false);
// Names each order's checkbox for screen readers: "Select order 1042"
protected readonly orderName = (order: Order) => `order ${order.id}`;
// The selection empties when the filters change, and keeps through a sort
protected readonly $selected = linkedSignal<Order[], Map<number, Order>>({ source: this.$orders, computation: () => new Map() });
protected readonly $selectedSales = computed(() => MONEY.format(sum([...this.$selected().values()], order => order.sales)));
protected readonly $selectionText = computed(() => `${plural(this.$selected().size, 'order')} selected`);
protected readonly $copyAllText = computed(() => `Copy ${plural(this.$orders().length, 'order')} to the clipboard`);
// The selection button goes with the selection, so focus goes to the Actions button beside it
protected clearSelection() {
this.$selected.set(new Map());
afterNextRender(
() => {
this.actionsButton()?.nativeElement.focus();
},
{ injector: this.injector },
);
}
// The table measures the rows it has room for, so it loads once its tab shows
protected loadOrders() {
void this.table().load();
}
protected openOrder(order: Order) {
this.dialogs.openTemplateModal(this.details(), { $implicit: order }, { header: { title: `Order ${order.id}`, allowClose: true }, width: '24rem' });
}
// The selected orders, or every order the filters keep, in the table's order
protected async copyOrders(selectedOnly: boolean) {
const selected = this.$selected();
const orders = sortOrders(selectedOnly ? this.$orders().filter(order => selected.has(order.id)) : this.$orders(), this.$sort());
const lines = orders.map(order => [order.id, isoDay(order.date), order.customer, order.region, order.channel, order.product, order.category, order.quantity, order.sales, order.profit].join('\t'));
try {
await this.clipboard.writeText(['Order\tDate\tCustomer\tRegion\tChannel\tProduct\tCategory\tQuantity\tSales\tProfit', ...lines].join('\n'));
this.snacks.openSnack(`Copied ${plural(orders.length, 'order')} to the clipboard`, 3000, 'success');
} catch {
// the clipboard service showed why in a snack of its own
}
}
// #endregion
}The enhanced table
app-enhanced-table frames a table, which it finds anywhere in its content. Layout & Sorting stripes the rows, and shows, hides, moves and pins the columns; Save keeps the layout and the sort in the viewer's browser, and Reset goes back to the saved layout or the default. A column moves by its handle, dragged, or focused and moved with the up and down arrows. Opening a panel puts the focus in it; Escape in it closes it, and the focus goes back to its button.
| Input, output or template | What it does |
|---|---|
uniqueId | Required. Names the layout a viewer saves |
selectionButtonText | The selection button's text; the button shows while rows are selected, when there is a selection menu |
searchLabel, [(search)] | The search field's name, without which there is none, and its text |
activeFilters, (clearFilters) | The number the Filters button shows, and Clear all filters |
drawerWidth | The drawer's width beside the content, 20rem by default |
(drawerOpened) | The panel the drawer opened on, filter or layout |
ng-template headerBeforeSelect, headerAfterSelect | The header row's content left and right of the selection button |
ng-template buttonMenu selectMenuButtons | The selection button's menu |
ng-template filterPanel | The filters in the drawer |
It moves columns with @angular/cdk/drag-drop, so an app that copies it installs the package at its Angular major:
npm install @angular/cdk@22import type { CdkDragDrop } from '@angular/cdk/drag-drop';
import { DragDropModule, moveItemInArray } from '@angular/cdk/drag-drop';
import { isPlatformBrowser, NgTemplateOutlet } from '@angular/common';
import type { AfterContentInit, WritableSignal } from '@angular/core';
import {
afterNextRender,
ChangeDetectionStrategy,
Component,
computed,
contentChild,
DestroyRef,
Directive,
effect,
ElementRef,
HostListener,
inject,
Injector,
input,
model,
output,
PLATFORM_ID,
signal,
TemplateRef,
viewChild,
} from '@angular/core';
import { TableauUiButtonModule } from 'tableau-ui-angular/button';
import { TableauUiCheckboxModule } from 'tableau-ui-angular/checkbox';
import { TableauUiCommonModule } from 'tableau-ui-angular/common';
import { DialogService } from 'tableau-ui-angular/dialog';
import { TableauUiDrawerModule } from 'tableau-ui-angular/drawer';
import { TableauUiFormFieldModule } from 'tableau-ui-angular/form-field';
import { TableauUiIconModule } from 'tableau-ui-angular/icon';
import { ButtonMenuDirective, TableauUiMenuModule } from 'tableau-ui-angular/menu';
import { TableauUiMenuButtonModule } from 'tableau-ui-angular/menu-button';
import type { HeaderContext } from 'tableau-ui-angular/table';
import { TableauUiTableModule, TableComponent } from 'tableau-ui-angular/table';
import { TableauUiTooltipModule } from 'tableau-ui-angular/tooltip';
import type { DataSort } from 'tableau-ui-angular/virtualize';
/** Content for the header row, left of the selection button */
@Directive({ selector: 'ng-template[headerBeforeSelect]' })
export class HeaderBeforeSelectDirective {
readonly template = inject<TemplateRef<unknown>>(TemplateRef);
}
/** Content for the header row, right of the selection button */
@Directive({ selector: 'ng-template[headerAfterSelect]' })
export class HeaderAfterSelectDirective {
readonly template = inject<TemplateRef<unknown>>(TemplateRef);
}
/** The filters, which the Filters button shows in the drawer */
@Directive({ selector: 'ng-template[filterPanel]' })
export class FilterPanelDirective {
readonly template = inject<TemplateRef<unknown>>(TemplateRef);
}
/** The menu of the selection button, on a `buttonMenu` template: its items act on the selected rows */
@Directive({ selector: 'ng-template[buttonMenu][selectMenuButtons]' })
export class SelectMenuButtonsDirective {
readonly menu = inject(ButtonMenuDirective);
}
type Panel = 'filter' | 'layout';
// A column in the layout panel: whether it shows, and its place
interface ColumnInfo<TData> {
id: string;
propertyName: string | undefined;
template: TemplateRef<{ $implicit: HeaderContext<TData> }> | undefined;
headerContext: HeaderContext<TData>;
$isShowing: WritableSignal<boolean>;
$order: WritableSignal<number>;
}
// What Save keeps in the viewer's browser, and Reset goes back to: every column in its order, and the hidden ones,
// so a column the table gains later shows, at the end
interface LayoutState {
striped: boolean;
order: string[];
hidden: string[];
pinnedLeftColumn: string | undefined;
pinnedRightColumn: string | undefined;
sort: DataSort[];
}
const sameSort = (a: readonly DataSort[], b: readonly DataSort[]) => a.length === b.length && a.every((sort, index) => sort.property === b[index].property && sort.direction === b[index].direction);
const sameLayout = (a: LayoutState, b: LayoutState) =>
a.striped === b.striped &&
a.order.join() === b.order.join() &&
[...a.hidden].sort().join() === [...b.hidden].sort().join() &&
a.pinnedLeftColumn === b.pinnedLeftColumn &&
a.pinnedRightColumn === b.pinnedRightColumn &&
sameSort(a.sort, b.sort);
// A saved layout, its fields checked one by one: a field that is missing or of the wrong type takes the default's
function readLayout(text: string, defaults: LayoutState): LayoutState | undefined {
const value: unknown = JSON.parse(text);
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return undefined;
}
const saved = value as Record<string, unknown>;
const ids = (field: unknown) => (Array.isArray(field) && field.every(item => typeof item === 'string') ? field : undefined);
const column = (field: unknown) => (typeof field === 'string' ? field : undefined);
const sorts = (field: unknown) =>
Array.isArray(field) &&
field.every(
(sort: unknown) =>
typeof sort === 'object' && sort !== null && typeof (sort as DataSort).property === 'string' && ((sort as DataSort).direction === 'asc' || (sort as DataSort).direction === 'desc'),
)
? (field as DataSort[])
: undefined;
return {
striped: typeof saved['striped'] === 'boolean' ? saved['striped'] : defaults.striped,
order: ids(saved['order']) ?? defaults.order,
hidden: ids(saved['hidden']) ?? defaults.hidden,
pinnedLeftColumn: column(saved['pinnedLeftColumn']),
pinnedRightColumn: column(saved['pinnedRightColumn']),
sort: sorts(saved['sort']) ?? defaults.sort,
};
}
// The inputs whose picker the browser opens, and closes on Escape
const PICKERS = ['date', 'datetime-local', 'month', 'time', 'week'];
let instances = 0;
/**
* A table's frame: a header row with a selection button, a search, Filters and Layout & Sorting, and a drawer for
* the filters or the layout. The content holds the table; it may hold more, as the dashboard's does.
*/
@Component({
selector: 'app-enhanced-table',
imports: [
DragDropModule,
NgTemplateOutlet,
TableauUiButtonModule,
TableauUiCheckboxModule,
TableauUiCommonModule,
TableauUiDrawerModule,
TableauUiFormFieldModule,
TableauUiIconModule,
TableauUiMenuModule,
TableauUiMenuButtonModule,
TableauUiTableModule,
TableauUiTooltipModule,
],
templateUrl: './enhanced-table.component.html',
styleUrl: './enhanced-table.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EnhancedTableComponent<TData> implements AfterContentInit {
private readonly dialogs = inject(DialogService);
private readonly injector = inject(Injector);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
// names the panel's labels apart from another table's
protected readonly id = `enhanced-table-${++instances}`;
// #region Content
protected readonly $headerBeforeSelect = contentChild(HeaderBeforeSelectDirective);
protected readonly $headerAfterSelect = contentChild(HeaderAfterSelectDirective);
protected readonly $selectMenuButtons = contentChild(SelectMenuButtonsDirective);
protected readonly $filterPanel = contentChild(FilterPanelDirective);
protected readonly $table = contentChild.required<TableComponent<TData>>(TableComponent);
private readonly filterToggle = viewChild.required<unknown, ElementRef<HTMLElement>>('filterToggle', { read: ElementRef });
private readonly layoutToggle = viewChild.required<unknown, ElementRef<HTMLElement>>('layoutToggle', { read: ElementRef });
private readonly panel = viewChild.required<ElementRef<HTMLElement>>('panel');
private readonly panelHeading = viewChild<ElementRef<HTMLElement>>('panelHeading');
private readonly searchField = viewChild<ElementRef<HTMLInputElement>>('searchField');
// #endregion
// #region Inputs and outputs
/** Names the layout the viewer saves, in their browser's storage */
readonly $uniqueId = input.required<string>({ alias: 'uniqueId' });
/** The selection button's text, such as "2 orders selected"; the button shows while rows are selected */
readonly $selectionButtonText = input('', { alias: 'selectionButtonText' });
/** The search field's name; without one, the header has no search */
readonly $searchLabel = input<string | undefined>(undefined, { alias: 'searchLabel' });
/** The search's text */
readonly $search = model('', { alias: 'search' });
/** How many filters are in use, which the Filters button shows; Clear all filters needs one */
readonly $activeFilters = input(0, { alias: 'activeFilters' });
/** The drawer's width beside the content; a narrow table's drawer covers it */
readonly $drawerWidth = input('20rem', { alias: 'drawerWidth' });
/** Clear all filters was clicked */
readonly clearFilters = output();
/** The drawer opened on this panel */
readonly drawerOpened = output<Panel>();
// #endregion
// #region Drawer
protected readonly $drawerOpen = signal(false);
protected readonly $drawerMode = signal<Panel>('filter');
// Whether the drawer fits beside the content; on the server, which lays nothing out, it doesn't
protected readonly $wide = signal(false);
constructor() {
// In the browser, once drawn, and each time the width changes
const destroyRef = inject(DestroyRef);
afterNextRender(() => {
const observer = new ResizeObserver(() => {
this.$wide.set(this.host.clientWidth >= 48 * parseFloat(getComputedStyle(this.host).fontSize));
});
observer.observe(this.host);
destroyRef.onDestroy(() => {
observer.disconnect();
});
});
}
// The drawer comes after the content, which can hold thousands of rows, so focus goes to the panel once it shows
protected toggleDrawer(mode: Panel) {
if (this.$drawerOpen() && this.$drawerMode() === mode) {
this.closeDrawer();
return;
}
this.$drawerMode.set(mode);
this.$drawerOpen.set(true);
this.drawerOpened.emit(mode);
afterNextRender(
() => {
this.panelHeading()?.nativeElement.focus();
},
{ injector: this.injector },
);
}
/**
* Closes the drawer, and focus goes back to the button that opens its panel. The drawer would put it back on the
* element focused when it opened, the other button once the panels switch, so this moves it first
*/
closeDrawer() {
this.$drawerOpen.set(false);
this.focusToggle(this.$drawerMode());
}
// Escape in the panel closes it, unless a select's options or a menu over it are open, or it comes from a date or
// time input, whose own picker Escape closes: the key can reach the page with the picker already shut
@HostListener('keydown.escape', ['$event'])
protected escape(event: Event) {
if (this.dialogs.dialogStack.some(entry => entry.args.closeOnEscape === true)) {
return;
}
if (event.target instanceof HTMLInputElement && PICKERS.includes(event.target.type)) {
return;
}
if (this.$drawerOpen() && event.target instanceof Node && this.panel().nativeElement.contains(event.target)) {
this.closeDrawer();
}
}
/** Focuses the button that opens the filters or the layout */
focusToggle(panel: Panel) {
(panel === 'filter' ? this.filterToggle() : this.layoutToggle()).nativeElement.focus();
}
protected searchInput(event: Event) {
this.$search.set((event.target as HTMLInputElement).value);
}
// The clear button goes with the text, so focus goes back to the search
protected clearSearch() {
this.$search.set('');
this.searchField()?.nativeElement.focus();
}
// #endregion
// #region Layout & Sorting
private readonly $storageKey = computed(() => `enhanced-table-layout-${this.$uniqueId()}`);
private readonly $defaultLayout = signal<LayoutState | undefined>(undefined);
protected readonly $savedLayout = signal<LayoutState | undefined>(undefined);
protected readonly $columns = signal<ColumnInfo<TData>[]>([]);
protected readonly $orderedColumns = computed(() => [...this.$columns()].sort((a, b) => a.$order() - b.$order()));
// What a screen reader says once a key moves a column
protected readonly $moved = signal('');
private currentLayout(): LayoutState {
const table = this.$table();
const all = table.$columnDefs().map(column => column.$id());
const shown = table.$displayedColumns() ?? all;
const columns = this.$orderedColumns();
return {
striped: table.$striped(),
order: columns.length > 0 ? columns.map(column => column.id) : [...shown, ...all.filter(id => !shown.includes(id))],
hidden: columns.length > 0 ? columns.filter(column => !column.$isShowing()).map(column => column.id) : all.filter(id => !shown.includes(id)),
pinnedLeftColumn: table.$pinnedLeftColumn(),
pinnedRightColumn: table.$pinnedRightColumn(),
sort: table.$sort(),
};
}
// The layout the table starts with is the default; the viewer's saved one, when the browser has it, replaces it
ngAfterContentInit(): void {
const layout = this.currentLayout();
this.$defaultLayout.set(layout);
this.$savedLayout.set(this.readSavedLayout(layout));
this.resetLayout();
}
// The table shows the columns marked to show, in their order
private readonly showColumns = effect(() => {
const columns = this.$orderedColumns().filter(column => column.$isShowing());
if (this.$columns().length > 0) {
this.$table().$displayedColumns.set(columns.map(column => column.id));
}
});
protected readonly $layoutChanged = computed(() => {
const layout = this.$savedLayout() ?? this.$defaultLayout();
return layout !== undefined && !sameLayout(layout, this.currentLayout());
});
// Never on the server. A browser that blocks storage, text that isn't a layout, or a layout that would hide every
// column leaves the default
private readSavedLayout(defaults: LayoutState): LayoutState | undefined {
if (!this.isBrowser) {
return undefined;
}
try {
const saved = localStorage.getItem(this.$storageKey());
const layout = saved === null ? undefined : readLayout(saved, defaults);
return layout !== undefined && defaults.order.some(id => !layout.hidden.includes(id)) ? layout : undefined;
} catch {
return undefined;
}
}
// A browser that blocks storage keeps the layout for this visit only
protected saveLayout() {
const layout = this.currentLayout();
try {
localStorage.setItem(this.$storageKey(), JSON.stringify(layout));
} catch {
// the saved layout lasts until the page closes
}
this.$savedLayout.set(layout);
}
protected async resetToDefault() {
const confirmed = await this.dialogs.openConfirmationMessageDialog('Reset to the default layout', 'This clears the layout and sort you saved.', 'error', 'Reset', 'Cancel', 'cancel');
if (!confirmed) {
return;
}
try {
localStorage.removeItem(this.$storageKey());
} catch {
// nothing was saved
}
this.$savedLayout.set(undefined);
this.resetLayout();
}
// Back to the saved layout, or the default when none is saved. Columns it doesn't know go at the end, shown; a pin or
// a sort on a column the table no longer has is dropped, and the default sort holds when none of the sort is left
protected resetLayout() {
const table = this.$table();
const defaults = this.$defaultLayout()!;
const layout = this.$savedLayout() ?? defaults;
const columns = table.$columnDefs();
const ids = columns.map(column => column.$id());
const order = [...layout.order.filter(id => ids.includes(id)), ...ids.filter(id => !layout.order.includes(id))];
const shown = order.filter(id => !layout.hidden.includes(id));
const properties = columns.map(column => column.$propertyName() ?? column.$id());
const known = layout.sort.filter(item => properties.includes(item.property));
const sort = known.length === 0 && layout.sort.length > 0 ? defaults.sort : known;
table.$striped.set(layout.striped);
this.$columns.set(
columns.map(column => {
const index = order.indexOf(column.$id());
return {
id: column.$id(),
propertyName: column.$propertyName(),
template: column.$header()?.templateRef,
headerContext: column.buildHeaderContext(index, index === 0, index === order.length - 1, index % 2 === 0, index % 2 === 1, order.length),
$isShowing: signal(shown.includes(column.$id())),
$order: signal(index),
};
}),
);
table.$pinnedLeftColumn.set(layout.pinnedLeftColumn !== undefined && ids.includes(layout.pinnedLeftColumn) ? layout.pinnedLeftColumn : undefined);
table.$pinnedRightColumn.set(layout.pinnedRightColumn !== undefined && ids.includes(layout.pinnedRightColumn) ? layout.pinnedRightColumn : undefined);
if (!sameSort(table.$sort(), sort)) {
table.$sort.set(sort);
}
}
protected columnDropped(event: CdkDragDrop<unknown>) {
this.moveColumn(event.previousIndex, event.currentIndex);
}
// The up and down arrows on a column's handle move it, and the handle keeps the focus; the announcement names the
// column, so two moves to the same place say different things
protected moveByKey(event: KeyboardEvent, index: number) {
const to = event.key === 'ArrowUp' ? index - 1 : event.key === 'ArrowDown' ? index + 1 : index;
if (to === index) {
return;
}
event.preventDefault();
const column = this.$orderedColumns()[index];
if (!this.moveColumn(index, to)) {
return;
}
const name = this.host.querySelector(`[id="${this.id}-${column.id}"]`)?.textContent.trim() ?? column.id;
this.$moved.set(`${name} moved to place ${to + 1} of ${this.$columns().length}`);
afterNextRender(
() => {
this.host.querySelector<HTMLElement>(`[data-handle="${column.id}"]`)?.focus();
},
{ injector: this.injector },
);
}
private moveColumn(from: number, to: number) {
const columns = [...this.$orderedColumns()];
if (from === to || to < 0 || to >= columns.length) {
return false;
}
moveItemInArray(columns, from, to);
columns.forEach((column, index) => {
column.$order.set(index);
});
return true;
}
protected togglePin(side: 'left' | 'right', id: string) {
const pinned = side === 'left' ? this.$table().$pinnedLeftColumn : this.$table().$pinnedRightColumn;
pinned.set(pinned() === id ? undefined : id);
}
// #endregion
}