# CRUD list

A customer list paged, sorted and filtered on the server: a lazy `vig-table` with debounced search and a status filter, row actions in a `vig-menu`, a create and edit `vig-dialog` with a validated Reactive Form, and delete with the `Confirm` service and a `Toast`.

- Source: [apps/docs/src/app/recipes/crud-list](https://github.com/bakyurekk/vigdx/blob/main/apps/docs/src/app/recipes/crud-list)

## Live demo

The recipe running against its in-memory API (400 ms latency, 57 seeded customers). Turn on server errors to see the error state and the failed-save message.

A list of records the server pages, sorts and filters, with create, edit and delete. The example
manages customers; rename the domain and keep the structure.

## When to use

- A back-office list of records that can grow beyond a few hundred rows, so paging, sorting and
  filtering must happen on the server.
- Users search and filter the list, open a record to edit it in place, and delete records.
- For a handful of rows that never grow, drop `lazy` and let `vig-table` page and sort on the client
  (`[paginator]="true"` with all `items`); the rest of the recipe stays the same.
- When editing needs more than a few fields or its own URL, open a routed form page instead of the
  dialog (see the `form-page` recipe).

## Component choices

| Need                             | Component                                          | Why                                                                                                                               | Alternatives                                                |
| -------------------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| The list                         | `vig-table` with `lazy`, `totalRecords`, `loading` | Native table semantics, sortable headers with `aria-sort`, an embedded paginator, and one `lazyLoad` event for paging and sorting | Cards in a grid when rows are not comparable                |
| Row names                        | `vig-col rowHeader`                                | The name cell becomes `<th scope="row">`, so every row control is announced with its row                                          | —                                                           |
| Search                           | `vig-input type="search"` with `hideLabel`         | Keeps the label as the accessible name in a dense toolbar                                                                         | `vig-autocomplete` to pick one record                       |
| Status filter                    | `vig-select` with `clearable`                      | Three or more options; clearing means "all"                                                                                       | `vig-select-button` for two or three always-visible choices |
| Row actions                      | `vig-menu` behind an icon `vig-button`             | Keeps rows compact; the APG menu button pattern                                                                                   | Inline text buttons when there are only one or two actions  |
| Create and edit                  | `vig-dialog` with a Reactive Form                  | Short forms stay in context; the native `<dialog>` traps focus and restores it                                                    | A routed form page for long forms                           |
| Delete                           | `Confirm` service                                  | One promise-based confirmation, styled destructive with `variant: 'error'`                                                        | Undo toast for reversible deletes                           |
| Feedback                         | `Toast` service                                    | Non-blocking; queued while a modal is open                                                                                        | `vig-message` for errors that need the user's action        |
| Empty, no-match and error states | `vigTableEmpty` with `vig-empty-state`             | Explains the state and offers the next step inside the table                                                                      | `emptyMessage` for a plain sentence                         |

## Folder structure

### Angular CLI

```text
src/app/features/customers/
  data-access/
    customer.ts                    domain types and the query
    customers-api.ts               abstract API = DI token
    http-customers-api.ts          HttpClient implementation
    in-memory-customers-api.ts     seeded fake for demos and tests
    customers-store.ts             signal store of the screen
  feature/
    customer-list-page.ts          routed smart page
    customers.routes.ts
  ui/
    customer-filters.ts            presentational
    customer-table.ts              presentational
    customer-form-dialog.ts        presentational
```

Wire the feature into `src/app/app.routes.ts` and bind the API there:

```ts title="app.routes.ts"
import { Routes } from '@angular/router';
import { CustomersApi } from './features/customers/data-access/customers-api';
import { HttpCustomersApi } from './features/customers/data-access/http-customers-api';

export const routes: Routes = [
  {
    path: 'customers',
    providers: [{ provide: CustomersApi, useClass: HttpCustomersApi }],
    loadChildren: () =>
      import('./features/customers/feature/customers.routes').then((m) => m.customersRoutes),
  },
];
```

`HttpCustomersApi` needs `provideHttpClient(withFetch())` in `app.config.ts`. Without a backend yet,
bind `InMemoryCustomersApi` instead (and list it in `providers` so it can be injected by class too).

### Nx

One library per folder, tagged so the module boundary rule keeps the layers apart:

```bash
npx nx g @nx/angular:library --directory=libs/customers/data-access --name=customers-data-access --tags=type:data-access,scope:customers --prefix=app --no-interactive
npx nx g @nx/angular:library --directory=libs/customers/feature-list --name=customers-feature-list --tags=type:feature,scope:customers --prefix=app --no-interactive
npx nx g @nx/angular:library --directory=libs/customers/ui --name=customers-ui --tags=type:ui,scope:customers --prefix=app --no-interactive
```

```text
libs/customers/
  data-access/src/lib/   customer.ts, customers-api.ts, http-customers-api.ts,
                         in-memory-customers-api.ts, customers-store.ts
  feature-list/src/lib/  customer-list-page.ts, customers.routes.ts
  ui/src/lib/            customer-filters.ts, customer-table.ts, customer-form-dialog.ts
```

Export the public pieces from each library's `src/index.ts`, replace the relative imports
(`../data-access/customer`) with the library aliases (`@<workspace>/customers-data-access`), and
load `customersRoutes` from the app exactly as in the Angular CLI example. The
[setup guide for Nx](https://github.com/bakyurekk/vigdx/blob/main/skills/vigdx-ui/references/setup-nx.md)
lists the `depConstraints` that enforce `feature → ui, data-access` and `ui → data-access` (types
only).

## Key decisions

- **The server owns the list.** `vig-table` runs in `lazy` mode: it renders the page it is given and
  emits `lazyLoad` once on start and after every paging or sorting change. The store turns that into
  the query; `totalRecords` sizes the paginator.
- **One query signal, one resource.** `CustomersStore` keeps the whole query (offset, page size,
  sort, search, status) in one signal with a structural `equal`, and loads it with `rxResource`.
  A changed query cancels the request in flight; an unchanged one (the table re-reporting the same
  page) does not refetch.
- **Debounced search.** The input reports every keystroke; the store updates the query 300 ms after
  typing pauses and jumps back to the first page. Filters also reset to the first page.
- **No flicker.** The store keeps the last page on screen while the next one loads, and the table
  shows its loading overlay on top (`loading` also disables the paginator).
- **Refetch after every mutation.** Creating, editing or deleting calls the API, then reloads the
  current page. The server decides where a new or renamed customer sorts and what the total is, so
  patching the list locally (optimistic updates) would show rows the server would not. Optimistic
  updates are worth it when latency is high and the list order is stable: update the resource with
  `value.update()`, call the API, and reload or roll back on error.
- **Errors stay where the user is.** A failed load shows an error state with a retry inside the
  table. A failed save keeps the dialog open with the user's input and a message; toasts would wait
  until the dialog closes. A failed delete raises an error toast. Every error text is a translatable label
  (`errorTitle`, `errorDescription`); the technical `error.message` never reaches the screen.
- **Dependency inversion.** The store and pages depend on the abstract `CustomersApi`; the app binds
  `HttpCustomersApi`, demos and tests bind `InMemoryCustomersApi` (seeded, deterministic, with
  simulated latency and failures).
- **Smart page, dumb UI.** `CustomerListPage` only wires the store to the components and turns
  events into store calls, confirmations and toasts. The `ui/` components take inputs, emit outputs
  and inject nothing; their texts come in a `labels` input for translation.

## Accessibility

- The table has a `caption`, sortable headers announce their sort, and the name column is a row
  header, so the actions button of each row is named "Actions for Ada Lovelace".
- Search and status keep their labels as accessible names while hidden (`hideLabel`), inside a search
  landmark (`role="search"`).
- The dialog is a native modal `<dialog>`: focus moves in, stays in, and returns to the button that
  opened it. A failed submit marks every field touched and moves focus to the first invalid one with
  `focusFirstInvalid`; each error is linked through `aria-describedby`.
- The delete confirmation focuses the safe choice, and its accept button is styled destructively. After a
  delete removes the row (and the button that had focus), focus moves to the page heading
  (`tabindex="-1"`) instead of falling to `<body>`.
- Status badges carry text, not only color; everything works in forced-colors mode because the kit's
  focus rings and borders do.
- Every text, including the kit components' labels, can be translated: pass `labels` to the `ui/`
  components and configure the kit with `provideVigdxUi({ locale })`.

## Performance

- Every component is `OnPush` and reads signals; the page re-renders only what changed.
- `vig-table` tracks rows by `rowId`, so a refetch keeps unchanged rows' DOM.
- The feature is lazy-loaded with `loadChildren`; only the page's chunk loads on navigation.
- Row menus are built once per page of rows in a `computed`, not on every change detection.
- Only one page of rows is ever in memory; the debounce keeps typing from flooding the server.

## Definition of done

- [ ] `nx build <app>` (or `ng build`) succeeds without warnings from the feature.
- [ ] `nx lint` passes, including the module boundary rule in Nx workspaces.
- [ ] The store and page specs pass: initial load, paging and sorting reach the query, debounced
      search, create with validation errors then success, edit, delete with confirmation, error and
      retry.
- [ ] axe reports no violations on the page in light and dark mode, with the dialog open too.
- [ ] Keyboard only: search, filter, sort, page, open a row menu, edit, save, delete and cancel.
- [ ] No hard-coded colors; every user-facing text comes from `labels` or a text constant.

## Source files

```typescript title="data-access/customer.ts"
/** Lifecycle of a customer account. */
export type CustomerStatus = 'active' | 'lead' | 'inactive';

export const CUSTOMER_STATUSES: readonly CustomerStatus[] = ['active', 'lead', 'inactive'];

export interface Customer {
  id: string;
  name: string;
  email: string;
  company: string;
  status: CustomerStatus;
  /** Calendar date the account was created, `YYYY-MM-DD`. */
  createdAt: string;
}

/** What the create and edit form submits; the server owns `id` and `createdAt`. */
export type CustomerDraft = Omit<Customer, 'id' | 'createdAt'>;

/** Columns the server can sort by. */
export type CustomerSortField = 'name' | 'company' | 'status' | 'createdAt';

export interface CustomerSort {
  field: CustomerSortField;
  direction: 'asc' | 'desc';
}

/** One page request: offset paging, sorting and the filters of the toolbar. */
export interface CustomerQuery {
  first: number;
  rows: number;
  sort: CustomerSort | null;
  /** Free text matched against name, email and company; `''` for none. */
  search: string;
  status: CustomerStatus | null;
}

/** One page of results plus the total the paginator needs. */
export interface CustomerPage {
  items: Customer[];
  total: number;
}
```

````typescript title="data-access/customers-api.ts"
import type { Observable } from 'rxjs';

import type { Customer, CustomerDraft, CustomerPage, CustomerQuery } from './customer';

/**
 * The customers backend as the screen needs it. Components and the store
 * depend on this abstraction only; the app binds an implementation:
 *
 * ```ts
 * providers: [{ provide: CustomersApi, useClass: HttpCustomersApi }]
 * ```
 *
 * The abstract class doubles as the DI token, so no separate
 * `InjectionToken` is needed.
 */
export abstract class CustomersApi {
  /** One page of customers matching the query. */
  abstract list(query: CustomerQuery): Observable<CustomerPage>;
  abstract create(draft: CustomerDraft): Observable<Customer>;
  abstract update(id: string, draft: CustomerDraft): Observable<Customer>;
  abstract remove(id: string): Observable<void>;
}
````

```typescript title="data-access/customers-store.ts"
import { DestroyRef, Injectable, computed, inject, linkedSignal, signal } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';
import { firstValueFrom } from 'rxjs';

import type {
  Customer,
  CustomerDraft,
  CustomerPage,
  CustomerQuery,
  CustomerSort,
  CustomerStatus,
} from './customer';
import { CustomersApi } from './customers-api';

/** How long typing pauses before the search reaches the server. */
export const SEARCH_DEBOUNCE_MS = 300;

export const INITIAL_CUSTOMER_QUERY: CustomerQuery = {
  first: 0,
  rows: 10,
  sort: null,
  search: '',
  status: null,
};

const EMPTY_PAGE: CustomerPage = { items: [], total: 0 };

function sameQuery(a: CustomerQuery, b: CustomerQuery): boolean {
  return (
    a.first === b.first &&
    a.rows === b.rows &&
    a.search === b.search &&
    a.status === b.status &&
    a.sort?.field === b.sort?.field &&
    a.sort?.direction === b.sort?.direction
  );
}

/**
 * State of the customers screen: the query (paging, sorting, filters), the
 * page loaded for it, and the mutations. Provided by the page component, so
 * it lives exactly as long as the screen.
 *
 * Reads go through `rxResource`, which reloads whenever the query changes and
 * cancels the request it supersedes. Mutations refetch the current page
 * afterwards: the server owns sorting, paging and the total.
 */
@Injectable()
export class CustomersStore {
  private readonly api = inject(CustomersApi);

  private readonly querySignal = signal(INITIAL_CUSTOMER_QUERY, { equal: sameQuery });
  /** The query of the page on screen; equal updates do not refetch. */
  readonly query = this.querySignal.asReadonly();

  private readonly searchTermSignal = signal('');
  /** The search text as typed (the query follows it after a debounce). */
  readonly searchTerm = this.searchTermSignal.asReadonly();

  private readonly page = rxResource({
    params: () => this.query(),
    stream: ({ params }) => this.api.list(params),
  });

  /** The last page that arrived, kept while the next one loads so rows do not flash away. */
  private readonly lastPage = linkedSignal<CustomerPage | undefined, CustomerPage>({
    source: () => (this.page.hasValue() ? this.page.value() : undefined),
    computation: (page, previous) => page ?? previous?.value ?? EMPTY_PAGE,
  });

  readonly loading = this.page.isLoading;
  /** The load error, if the last request failed. */
  readonly error = computed(() => (this.page.status() === 'error' ? this.page.error() : undefined));
  readonly customers = computed(() => (this.error() ? [] : this.lastPage().items));
  readonly total = computed(() => this.lastPage().total);
  readonly filtered = computed(() => !!this.query().search || !!this.query().status);

  private readonly savingSignal = signal(false);
  readonly saving = this.savingSignal.asReadonly();

  private searchTimer: ReturnType<typeof setTimeout> | undefined;

  constructor() {
    inject(DestroyRef).onDestroy(() => clearTimeout(this.searchTimer));
  }

  /** Paging and sorting, as the lazy table reports them. */
  setPage(first: number, rows: number, sort: CustomerSort | null): void {
    this.querySignal.update((query) => ({ ...query, first, rows, sort }));
  }

  /** Debounced: the query (and the request) follow once typing pauses. */
  setSearch(term: string): void {
    this.searchTermSignal.set(term);
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(
      () => this.querySignal.update((query) => ({ ...query, search: term.trim(), first: 0 })),
      SEARCH_DEBOUNCE_MS,
    );
  }

  setStatus(status: CustomerStatus | null): void {
    this.querySignal.update((query) => ({ ...query, status, first: 0 }));
  }

  clearFilters(): void {
    clearTimeout(this.searchTimer);
    this.searchTermSignal.set('');
    this.querySignal.update((query) => ({ ...query, search: '', status: null, first: 0 }));
  }

  /** Loads the current query again, e.g. after an error. */
  reload(): void {
    this.page.reload();
  }

  /** Creates (no `id`) or updates a customer, then refetches the page. */
  async save(draft: CustomerDraft, id?: string): Promise<Customer> {
    this.savingSignal.set(true);
    try {
      const saved = await firstValueFrom(id ? this.api.update(id, draft) : this.api.create(draft));
      this.page.reload();
      return saved;
    } finally {
      this.savingSignal.set(false);
    }
  }

  /** Deletes a customer, then refetches the page. */
  async remove(customer: Customer): Promise<void> {
    await firstValueFrom(this.api.remove(customer.id));
    this.page.reload();
  }
}
```

```typescript title="data-access/customers-store.spec.ts"
import { ApplicationRef, provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Observable, of, throwError } from 'rxjs';

import type { Customer, CustomerPage, CustomerQuery } from './customer';
import { CustomersApi } from './customers-api';
import { CustomersStore, INITIAL_CUSTOMER_QUERY, SEARCH_DEBOUNCE_MS } from './customers-store';

const ADA: Customer = {
  id: 'C-1',
  name: 'Ada Lovelace',
  email: 'ada@example.com',
  company: 'Analytical',
  status: 'active',
  createdAt: '2026-01-02',
};

describe('CustomersStore', () => {
  let api: {
    list: ReturnType<typeof vi.fn>;
    create: ReturnType<typeof vi.fn>;
    update: ReturnType<typeof vi.fn>;
    remove: ReturnType<typeof vi.fn>;
  };

  beforeEach(() => {
    api = {
      list: vi.fn((): Observable<CustomerPage> => of({ items: [ADA], total: 1 })),
      create: vi.fn(() => of({ ...ADA, id: 'C-2' })),
      update: vi.fn(() => of(ADA)),
      remove: vi.fn(() => of(undefined)),
    };
    TestBed.configureTestingModule({
      providers: [
        provideZonelessChangeDetection(),
        CustomersStore,
        { provide: CustomersApi, useValue: api },
      ],
    });
  });

  afterEach(() => vi.useRealTimers());

  async function setup() {
    const store = TestBed.inject(CustomersStore);
    await TestBed.inject(ApplicationRef).whenStable();
    return store;
  }

  const lastQuery = (): CustomerQuery => api.list.mock.lastCall?.[0];

  it('loads the first page for the initial query', async () => {
    const store = await setup();
    expect(api.list).toHaveBeenCalledTimes(1);
    expect(lastQuery()).toEqual(INITIAL_CUSTOMER_QUERY);
    expect(store.customers()).toEqual([ADA]);
    expect(store.total()).toBe(1);
    expect(store.loading()).toBe(false);
  });

  it('requests the page and sort the table reports, and ignores repeats', async () => {
    const store = await setup();
    store.setPage(20, 10, { field: 'name', direction: 'desc' });
    await TestBed.inject(ApplicationRef).whenStable();
    expect(lastQuery()).toMatchObject({ first: 20, rows: 10, sort: { field: 'name' } });

    store.setPage(20, 10, { field: 'name', direction: 'desc' });
    await TestBed.inject(ApplicationRef).whenStable();
    expect(api.list).toHaveBeenCalledTimes(2);
  });

  it('debounces the search and goes back to the first page', async () => {
    const store = await setup();
    store.setPage(30, 10, null);
    await TestBed.inject(ApplicationRef).whenStable();

    vi.useFakeTimers();
    store.setSearch('ad');
    store.setSearch('ada ');
    expect(store.searchTerm()).toBe('ada ');
    vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS - 1);
    TestBed.tick();
    expect(lastQuery().search).toBe('');

    vi.advanceTimersByTime(1);
    TestBed.tick();
    vi.useRealTimers();
    await TestBed.inject(ApplicationRef).whenStable();
    expect(lastQuery()).toMatchObject({ search: 'ada', first: 0 });
    expect(store.filtered()).toBe(true);
  });

  it('filters by status and clears every filter', async () => {
    const store = await setup();
    store.setStatus('lead');
    await TestBed.inject(ApplicationRef).whenStable();
    expect(lastQuery()).toMatchObject({ status: 'lead', first: 0 });

    store.clearFilters();
    await TestBed.inject(ApplicationRef).whenStable();
    expect(lastQuery()).toMatchObject({ status: null, search: '' });
    expect(store.filtered()).toBe(false);
  });

  it('exposes a load error, keeps the total and recovers on reload', async () => {
    api.list.mockReturnValueOnce(throwError(() => new Error('offline')));
    const store = await setup();
    expect(store.error()?.message).toBe('offline');
    expect(store.customers()).toEqual([]);

    store.reload();
    await TestBed.inject(ApplicationRef).whenStable();
    expect(store.error()).toBeUndefined();
    expect(store.customers()).toEqual([ADA]);
  });

  it('creates and updates, then refetches the current page', async () => {
    const store = await setup();
    const draft = {
      name: 'Grace',
      email: 'grace@example.com',
      company: '',
      status: 'lead' as const,
    };

    const created = await store.save(draft);
    expect(api.create).toHaveBeenCalledWith(draft);
    expect(created.id).toBe('C-2');
    await TestBed.inject(ApplicationRef).whenStable();
    expect(api.list).toHaveBeenCalledTimes(2);

    await store.save(draft, 'C-1');
    expect(api.update).toHaveBeenCalledWith('C-1', draft);
    expect(store.saving()).toBe(false);
  });

  it('deletes, then refetches; a failed delete rejects', async () => {
    const store = await setup();
    await store.remove(ADA);
    expect(api.remove).toHaveBeenCalledWith('C-1');
    await TestBed.inject(ApplicationRef).whenStable();
    expect(api.list).toHaveBeenCalledTimes(2);

    api.remove.mockReturnValueOnce(throwError(() => new Error('conflict')));
    await expect(store.remove(ADA)).rejects.toThrow('conflict');
  });

  it('keeps the previous rows while the next page loads', async () => {
    const store = await setup();
    // Rendered, like the table does on screen.
    expect(store.customers()).toEqual([ADA]);
    let resolve!: (page: CustomerPage) => void;
    api.list.mockReturnValueOnce(
      new Observable<CustomerPage>((subscriber) => {
        resolve = (page) => {
          subscriber.next(page);
          subscriber.complete();
        };
      }),
    );
    store.setPage(10, 10, null);
    TestBed.tick();
    expect(store.loading()).toBe(true);
    expect(store.customers()).toEqual([ADA]);

    resolve({ items: [], total: 1 });
    await TestBed.inject(ApplicationRef).whenStable();
    expect(store.customers()).toEqual([]);
  });
});
```

```typescript title="data-access/http-customers-api.ts"
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { type Observable, map } from 'rxjs';

import type { Customer, CustomerDraft, CustomerPage, CustomerQuery } from './customer';
import type { CustomersApi } from './customers-api';

/** Base URL of the customers resource; adapt it to your backend. */
export const CUSTOMERS_URL = '/api/customers';

/**
 * `CustomersApi` over HTTP. Paging, sorting and filtering happen on the
 * server; the query travels as URL parameters:
 *
 * `GET /api/customers?offset=20&limit=10&sort=name&order=asc&q=ada&status=active`
 * → `{ "items": [...], "total": 57 }`
 *
 * Needs `provideHttpClient()` in the application config.
 */
@Injectable()
export class HttpCustomersApi implements CustomersApi {
  private readonly http = inject(HttpClient);

  list(query: CustomerQuery): Observable<CustomerPage> {
    let params = new HttpParams().set('offset', query.first).set('limit', query.rows);
    if (query.sort) {
      params = params.set('sort', query.sort.field).set('order', query.sort.direction);
    }
    if (query.search) params = params.set('q', query.search);
    if (query.status) params = params.set('status', query.status);
    return this.http.get<CustomerPage>(CUSTOMERS_URL, { params });
  }

  create(draft: CustomerDraft): Observable<Customer> {
    return this.http.post<Customer>(CUSTOMERS_URL, draft);
  }

  update(id: string, draft: CustomerDraft): Observable<Customer> {
    return this.http.put<Customer>(`${CUSTOMERS_URL}/${encodeURIComponent(id)}`, draft);
  }

  remove(id: string): Observable<void> {
    return this.http
      .delete(`${CUSTOMERS_URL}/${encodeURIComponent(id)}`)
      .pipe(map(() => undefined));
  }
}
```

```typescript title="data-access/http-customers-api.spec.ts"
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { firstValueFrom } from 'rxjs';

import { CUSTOMERS_URL, HttpCustomersApi } from './http-customers-api';

describe('HttpCustomersApi', () => {
  let api: HttpCustomersApi;
  let http: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        provideZonelessChangeDetection(),
        provideHttpClient(),
        provideHttpClientTesting(),
        HttpCustomersApi,
      ],
    });
    api = TestBed.inject(HttpCustomersApi);
    http = TestBed.inject(HttpTestingController);
  });

  afterEach(() => http.verify());

  it('sends paging, sorting and filters as query parameters', async () => {
    const page = firstValueFrom(
      api.list({
        first: 20,
        rows: 10,
        sort: { field: 'name', direction: 'desc' },
        search: 'ada',
        status: 'active',
      }),
    );
    const request = http.expectOne((r) => r.url === CUSTOMERS_URL);
    expect(request.request.method).toBe('GET');
    expect(request.request.params.toString()).toBe(
      'offset=20&limit=10&sort=name&order=desc&q=ada&status=active',
    );
    request.flush({ items: [], total: 0 });
    expect(await page).toEqual({ items: [], total: 0 });
  });

  it('leaves out empty filters and the sort', () => {
    api.list({ first: 0, rows: 25, sort: null, search: '', status: null }).subscribe();
    const request = http.expectOne((r) => r.url === CUSTOMERS_URL);
    expect(request.request.params.toString()).toBe('offset=0&limit=25');
    request.flush({ items: [], total: 0 });
  });

  it('creates, updates and deletes through the resource URL', async () => {
    const draft = { name: 'Ada', email: 'ada@example.com', company: '', status: 'lead' as const };

    api.create(draft).subscribe();
    const create = http.expectOne(CUSTOMERS_URL);
    expect(create.request.method).toBe('POST');
    expect(create.request.body).toEqual(draft);
    create.flush({ ...draft, id: 'C-1', createdAt: '2026-01-01' });

    api.update('C 1', draft).subscribe();
    const update = http.expectOne(`${CUSTOMERS_URL}/C%201`);
    expect(update.request.method).toBe('PUT');
    update.flush({ ...draft, id: 'C 1', createdAt: '2026-01-01' });

    const removed = firstValueFrom(api.remove('C-1'));
    const remove = http.expectOne(`${CUSTOMERS_URL}/C-1`);
    expect(remove.request.method).toBe('DELETE');
    remove.flush(null);
    expect(await removed).toBeUndefined();
  });
});
```

```typescript title="data-access/in-memory-customers-api.ts"
import { Injectable, InjectionToken, inject, signal } from '@angular/core';
import { type Observable, map, timer } from 'rxjs';

import {
  CUSTOMER_STATUSES,
  type Customer,
  type CustomerDraft,
  type CustomerPage,
  type CustomerQuery,
} from './customer';
import type { CustomersApi } from './customers-api';

/** Simulated network latency of `InMemoryCustomersApi` in ms; tests set 0. */
export const CUSTOMERS_API_LATENCY = new InjectionToken<number>('CUSTOMERS_API_LATENCY', {
  factory: () => 400,
});

const FIRST_NAMES = ['Ada', 'Grace', 'Linus', 'Margaret', 'Alan', 'Barbara', 'Dennis', 'Frances'];
const LAST_NAMES = ['Lovelace', 'Hopper', 'Torvalds', 'Hamilton', 'Turing', 'Liskov', 'Ritchie'];
const COMPANIES = ['Northwind', 'Contoso', 'Fabrikam', 'Tailspin', 'Wingtip', 'Litware'];

/** 57 customers, the same on every run (no randomness, no clock). */
function seed(): Customer[] {
  return Array.from({ length: 57 }, (_, i) => {
    const first = FIRST_NAMES[i % FIRST_NAMES.length];
    const last = LAST_NAMES[(i * 3) % LAST_NAMES.length];
    const company = COMPANIES[(i * 5) % COMPANIES.length];
    const month = String((i % 12) + 1).padStart(2, '0');
    const day = String((i % 28) + 1).padStart(2, '0');
    return {
      id: `C-${1001 + i}`,
      name: `${first} ${last}`,
      email: `${first}.${last}${i + 1}@${company}.example`.toLowerCase(),
      company,
      status: CUSTOMER_STATUSES[i % CUSTOMER_STATUSES.length],
      createdAt: `${2024 + (i % 3)}-${month}-${day}`,
    };
  });
}

function compare(a: Customer, b: Customer, query: CustomerQuery): number {
  if (!query.sort) return 0;
  const { field, direction } = query.sort;
  return (direction === 'asc' ? 1 : -1) * a[field].localeCompare(b[field]);
}

/**
 * `CustomersApi` over an in-memory list with simulated latency, so the screen
 * runs without a backend (demos, prototypes, tests). Behaves like the server
 * would: filters, sorts and pages, and answers with copies.
 */
@Injectable()
export class InMemoryCustomersApi implements CustomersApi {
  private readonly latency = inject(CUSTOMERS_API_LATENCY);
  private customers = seed();
  private nextId = this.customers.length + 1001;

  /** When true every request fails, to exercise the error and retry states. */
  readonly failing = signal(false);

  list(query: CustomerQuery): Observable<CustomerPage> {
    return this.respond(() => {
      const term = query.search.trim().toLocaleLowerCase();
      const matches = this.customers
        .filter((c) => !query.status || c.status === query.status)
        .filter(
          (c) =>
            !term ||
            [c.name, c.email, c.company].some((text) => text.toLocaleLowerCase().includes(term)),
        )
        .sort((a, b) => compare(a, b, query));
      const items = matches.slice(query.first, query.first + query.rows);
      return { items: items.map((c) => ({ ...c })), total: matches.length };
    });
  }

  create(draft: CustomerDraft): Observable<Customer> {
    return this.respond(() => {
      const customer: Customer = { ...draft, id: `C-${this.nextId++}`, createdAt: '2026-11-16' };
      this.customers = [customer, ...this.customers];
      return { ...customer };
    });
  }

  update(id: string, draft: CustomerDraft): Observable<Customer> {
    return this.respond(() => {
      const existing = this.customers.find((c) => c.id === id);
      if (!existing) throw new Error(`Customer ${id} not found`);
      const updated = { ...existing, ...draft };
      this.customers = this.customers.map((c) => (c.id === id ? updated : c));
      return { ...updated };
    });
  }

  remove(id: string): Observable<void> {
    return this.respond(() => {
      this.customers = this.customers.filter((c) => c.id !== id);
    });
  }

  /** Runs `work` once the latency has passed, like a request would. */
  private respond<T>(work: () => T): Observable<T> {
    return timer(this.latency).pipe(
      map(() => {
        if (this.failing()) throw new Error('The server is not responding.');
        return work();
      }),
    );
  }
}
```

```typescript title="feature/customer-list-page.ts"
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  Injector,
  afterNextRender,
  inject,
  signal,
  viewChild,
} from '@angular/core';
import { Button, ButtonIcon } from '@vigdx/ui/button';
import { Confirm } from '@vigdx/ui/confirm-dialog';
import { Icon } from '@vigdx/ui/icon';
import { Toast } from '@vigdx/ui/toast';

import type { Customer, CustomerDraft } from '../data-access/customer';
import { CustomersStore } from '../data-access/customers-store';
import { CustomerFilters } from '../ui/customer-filters';
import { CustomerFormDialog } from '../ui/customer-form-dialog';
import { CustomerTable } from '../ui/customer-table';

/** Texts of the page itself; the child components take theirs as `labels`. */
export const CUSTOMER_LIST_TEXT = {
  title: 'Customers',
  create: 'New customer',
  created: (name: string) => `${name} was added.`,
  updated: (name: string) => `${name} was updated.`,
  saveFailed: 'The customer could not be saved. Check your connection and try again.',
  deleteHeading: 'Delete customer?',
  deleteMessage: (name: string) => `${name} and their history will be deleted for good.`,
  deleteAccept: 'Delete',
  deleted: (name: string) => `${name} was deleted.`,
  deleteFailed: (name: string) => `${name} could not be deleted. Try again.`,
};

/**
 * The routed customers screen. Orchestration only: it wires the store to the
 * presentational components and turns their events into store calls,
 * confirmations and toasts. Needs `<vig-toaster />` and
 * `<vig-confirm-dialog />` in the app shell and a `CustomersApi` provider.
 */
@Component({
  selector: 'app-customer-list-page',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [CustomersStore],
  imports: [Button, ButtonIcon, Icon, CustomerFilters, CustomerFormDialog, CustomerTable],
  host: { class: 'flex flex-col gap-4' },
  template: `
    <div class="flex flex-wrap items-center justify-between gap-3">
      <!-- Focus target after a delete removed the row (and the button) focus was on. -->
      <h1
        #heading
        tabindex="-1"
        class="rounded-button text-h2 text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
      >
        {{ text.title }}
      </h1>
      <vig-button [label]="text.create" (click)="openCreate()">
        <vig-icon vigButtonIcon name="plus" />
      </vig-button>
    </div>

    <app-customer-filters
      [search]="store.searchTerm()"
      [status]="store.query().status"
      (searchChange)="store.setSearch($event)"
      (statusChange)="store.setStatus($event)"
    />

    <app-customer-table
      [customers]="store.customers()"
      [total]="store.total()"
      [query]="store.query()"
      [loading]="store.loading()"
      [error]="store.error()"
      [filtered]="store.filtered()"
      (pageChange)="store.setPage($event.first, $event.rows, $event.sort)"
      (edit)="openEdit($event)"
      (remove)="confirmRemove($event)"
      (create)="openCreate()"
      (retry)="store.reload()"
      (clearFilters)="store.clearFilters()"
    />

    <app-customer-form-dialog
      [(open)]="dialogOpen"
      [customer]="editing()"
      [saving]="store.saving()"
      [error]="saveError()"
      (save)="save($event)"
    />
  `,
})
export class CustomerListPage {
  protected readonly store = inject(CustomersStore);
  private readonly confirm = inject(Confirm);
  private readonly toast = inject(Toast);
  private readonly injector = inject(Injector);
  private readonly heading = viewChild.required<ElementRef<HTMLElement>>('heading');

  protected readonly text = CUSTOMER_LIST_TEXT;
  protected readonly dialogOpen = signal(false);
  /** The customer in the dialog; `null` while creating. */
  protected readonly editing = signal<Customer | null>(null);
  protected readonly saveError = signal<string | null>(null);

  protected openCreate(): void {
    this.editing.set(null);
    this.saveError.set(null);
    this.dialogOpen.set(true);
  }

  protected openEdit(customer: Customer): void {
    this.editing.set(customer);
    this.saveError.set(null);
    this.dialogOpen.set(true);
  }

  protected async save(draft: CustomerDraft): Promise<void> {
    const editing = this.editing();
    this.saveError.set(null);
    try {
      const saved = await this.store.save(draft, editing?.id);
      this.dialogOpen.set(false);
      // Toasts raised while the dialog is open wait until it has closed.
      this.toast.success(editing ? this.text.updated(saved.name) : this.text.created(saved.name));
    } catch {
      // The dialog stays open with the user's input; the message says why.
      this.saveError.set(this.text.saveFailed);
    }
  }

  protected async confirmRemove(customer: Customer): Promise<void> {
    const accepted = await this.confirm.ask({
      heading: this.text.deleteHeading,
      message: this.text.deleteMessage(customer.name),
      acceptLabel: this.text.deleteAccept,
      variant: 'error',
    });
    if (!accepted) return;
    try {
      await this.store.remove(customer);
      this.toast.success(this.text.deleted(customer.name));
      // The row and its actions button are gone; without this, focus would fall to <body>.
      afterNextRender(() => this.heading().nativeElement.focus(), { injector: this.injector });
    } catch {
      this.toast.error(this.text.deleteFailed(customer.name));
    }
  }
}
```

```typescript title="feature/customer-list-page.spec.ts"
import { ApplicationRef, provideZonelessChangeDetection } from '@angular/core';
import { type ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Confirm } from '@vigdx/ui/confirm-dialog';
import { provideVigdxUi } from '@vigdx/ui/core';
import { Toast } from '@vigdx/ui/toast';

import { CustomersApi } from '../data-access/customers-api';
import {
  CUSTOMERS_API_LATENCY,
  InMemoryCustomersApi,
} from '../data-access/in-memory-customers-api';
import { CustomerFormDialog } from '../ui/customer-form-dialog';
import { CustomerTable } from '../ui/customer-table';
import { CustomerListPage } from './customer-list-page';

describe('CustomerListPage', () => {
  const confirm = { ask: vi.fn() };
  const toast = { success: vi.fn(), error: vi.fn() };
  let fixture: ComponentFixture<CustomerListPage>;
  let api: InMemoryCustomersApi;
  let el: HTMLElement;

  beforeEach(async () => {
    // jsdom has no modal <dialog>; the kit opens dialogs with showModal().
    HTMLDialogElement.prototype.showModal ??= function (this: HTMLDialogElement) {
      this.setAttribute('open', '');
    };
    HTMLDialogElement.prototype.close ??= function (this: HTMLDialogElement) {
      this.removeAttribute('open');
      this.dispatchEvent(new Event('close'));
    };
    confirm.ask.mockReset();
    toast.success.mockReset();
    toast.error.mockReset();
    TestBed.configureTestingModule({
      imports: [CustomerListPage],
      providers: [
        provideZonelessChangeDetection(),
        provideVigdxUi(),
        InMemoryCustomersApi,
        { provide: CustomersApi, useExisting: InMemoryCustomersApi },
        { provide: CUSTOMERS_API_LATENCY, useValue: 0 },
        { provide: Confirm, useValue: confirm },
        { provide: Toast, useValue: toast },
      ],
    });
    api = TestBed.inject(InMemoryCustomersApi);
    vi.spyOn(api, 'list');
    fixture = TestBed.createComponent(CustomerListPage);
    el = fixture.nativeElement;
    await settle();
  });

  /** Lets the zero-latency API timers, pending promises and rendering finish. */
  async function settle(): Promise<void> {
    for (let i = 0; i < 3; i++) {
      await new Promise((resolve) => setTimeout(resolve));
      await TestBed.inject(ApplicationRef).whenStable();
    }
    await fixture.whenStable();
  }

  const rowNames = () =>
    Array.from(el.querySelectorAll('tbody th[scope="row"]')).map((th) => th.textContent?.trim());
  const lastQuery = () => vi.mocked(api.list).mock.lastCall?.[0];
  const dialog = () => fixture.debugElement.query(By.directive(CustomerFormDialog));
  const table = () => fixture.debugElement.query(By.directive(CustomerTable)).componentInstance;
  const field = (label: string) =>
    Array.from(dialog().nativeElement.querySelectorAll('vig-input')).find((input) =>
      (input as HTMLElement).textContent?.includes(label),
    ) as HTMLElement;
  function type(label: string, value: string): void {
    const input = field(label).querySelector('input') as HTMLInputElement;
    input.value = value;
    input.dispatchEvent(new Event('input'));
    input.dispatchEvent(new Event('blur'));
  }
  async function submitDialog(): Promise<void> {
    const form = dialog().nativeElement.querySelector('form') as HTMLFormElement;
    form.dispatchEvent(new Event('submit'));
    await settle();
  }

  it('loads the first page of customers into the lazy table', () => {
    expect(el.querySelector('h1')?.textContent).toContain('Customers');
    expect(rowNames()).toHaveLength(10);
    expect(lastQuery()).toMatchObject({ first: 0, rows: 10, sort: null });
    expect(el.textContent).toContain('1–10 / 57');
  });

  it('asks the server for the sorted and the next page', async () => {
    const sortName = el.querySelector<HTMLButtonElement>('th button');
    sortName?.click();
    await settle();
    expect(lastQuery()).toMatchObject({ first: 0, sort: { field: 'name', direction: 'asc' } });
    expect(rowNames()[0]).toBe('Ada Hamilton');

    el.querySelector<HTMLButtonElement>('button[aria-label="Next page"]')?.click();
    await settle();
    expect(lastQuery()).toMatchObject({ first: 10, sort: { field: 'name' } });
  });

  it('validates the create form, then creates and announces the customer', async () => {
    el.querySelector<HTMLElement>('vig-button button')?.click();
    await settle();
    expect(dialog().componentInstance.open()).toBe(true);

    await submitDialog();
    const name = field('Name').querySelector('input') as HTMLInputElement;
    expect(name.getAttribute('aria-invalid')).toBe('true');
    expect(document.activeElement).toBe(name);
    expect(field('Email').textContent).toContain('This field is required.');

    type('Name', 'Katherine Johnson');
    type('Email', 'katherine@nasa.example');
    await submitDialog();
    expect(dialog().componentInstance.open()).toBe(false);
    expect(toast.success).toHaveBeenCalledWith('Katherine Johnson was added.');
    expect(lastQuery()).toMatchObject({ first: 0 });
    expect(api.list).toHaveBeenCalledTimes(2);
  });

  it('edits a customer from the row actions', async () => {
    const [first] = (await firstPage()).items;
    table().edit.emit(first);
    await settle();
    expect((field('Name').querySelector('input') as HTMLInputElement).value).toBe(first.name);

    type('Name', 'Ada King');
    await submitDialog();
    expect(toast.success).toHaveBeenCalledWith('Ada King was updated.');
    expect(rowNames()).toContain('Ada King');
  });

  it('keeps the dialog open with a message when saving fails', async () => {
    table().create.emit();
    await settle();
    type('Name', 'Mary Jackson');
    type('Email', 'mary@nasa.example');
    api.failing.set(true);
    await submitDialog();
    expect(dialog().componentInstance.open()).toBe(true);
    expect(dialog().nativeElement.textContent).toContain('could not be saved');
    expect(toast.success).not.toHaveBeenCalled();
  });

  it('deletes after confirmation and reports the result', async () => {
    const [first] = (await firstPage()).items;
    confirm.ask.mockResolvedValueOnce(false);
    table().remove.emit(first);
    await settle();
    expect(confirm.ask).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error' }));
    expect(rowNames()).toContain(first.name);

    confirm.ask.mockResolvedValueOnce(true);
    table().remove.emit(first);
    await settle();
    expect(toast.success).toHaveBeenCalledWith(`${first.name} was deleted.`);
    expect(document.activeElement).toBe(el.querySelector('h1'));
    expect(el.textContent).toContain('1–10 / 56');
  });

  it('shows the error state and retries', async () => {
    api.failing.set(true);
    table().pageChange.emit({ first: 10, rows: 10, sort: null });
    await settle();
    expect(el.textContent).toContain('Customers could not be loaded');

    api.failing.set(false);
    const retry = Array.from(el.querySelectorAll('button')).find((b) =>
      b.textContent?.includes('Try again'),
    );
    retry?.click();
    await settle();
    expect(rowNames()).toHaveLength(10);
  });

  function firstPage() {
    return new Promise<{ items: { id: string; name: string }[] }>((resolve) =>
      api
        .list({ first: 0, rows: 10, sort: null, search: '', status: null })
        .subscribe((page) => resolve(page)),
    );
  }
});
```

````typescript title="feature/customers.routes.ts"
import type { Routes } from '@angular/router';

/**
 * Routes of the customers feature, lazy-loaded by the app:
 *
 * ```ts
 * {
 *   path: 'customers',
 *   providers: [{ provide: CustomersApi, useClass: HttpCustomersApi }],
 *   loadChildren: () => import('./features/customers/feature/customers.routes').then((m) => m.customersRoutes),
 * }
 * ```
 */
export const customersRoutes: Routes = [
  {
    path: '',
    title: 'Customers',
    loadComponent: () => import('./customer-list-page').then((m) => m.CustomerListPage),
  },
];
````

```typescript title="ui/customer-filters.ts"
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { InputField } from '@vigdx/ui/input-field';
import { Select, type SelectOption } from '@vigdx/ui/select';

import { CUSTOMER_STATUSES, type CustomerStatus } from '../data-access/customer';

export interface CustomerFiltersLabels {
  search: string;
  searchPlaceholder: string;
  status: string;
  allStatuses: string;
  statuses: Record<CustomerStatus, string>;
}

export const CUSTOMER_FILTERS_LABELS: CustomerFiltersLabels = {
  search: 'Search customers',
  searchPlaceholder: 'Search name, email or company',
  status: 'Status',
  allStatuses: 'All statuses',
  statuses: { active: 'Active', lead: 'Lead', inactive: 'Inactive' },
};

/**
 * Toolbar filters of the customer list. Presentational: shows the values it
 * is given and reports every change; debouncing is the store's job.
 */
@Component({
  selector: 'app-customer-filters',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputField, Select],
  // A search landmark. `role="search"` rather than `<search>`: same semantics,
  // and unit-test DOMs (jsdom) do not know the element yet.
  template: `
    <div
      role="search"
      class="flex flex-wrap items-center gap-3"
      [attr.aria-label]="labels().search"
    >
      <vig-input
        class="w-full sm:w-72"
        type="search"
        autocomplete="off"
        [label]="labels().search"
        [hideLabel]="true"
        [placeholder]="labels().searchPlaceholder"
        [value]="search()"
        (valueChange)="searchChange.emit($event)"
      />
      <vig-select
        class="w-full sm:w-44"
        [label]="labels().status"
        [hideLabel]="true"
        [placeholder]="labels().allStatuses"
        [clearable]="true"
        [options]="statusOptions()"
        [value]="status()"
        (valueChange)="statusChange.emit($event)"
      />
    </div>
  `,
})
export class CustomerFilters {
  readonly search = input('');
  readonly status = input<CustomerStatus | null>(null);
  readonly labels = input(CUSTOMER_FILTERS_LABELS);

  readonly searchChange = output<string>();
  readonly statusChange = output<CustomerStatus | null>();

  protected readonly statusOptions = computed<SelectOption<CustomerStatus>[]>(() =>
    CUSTOMER_STATUSES.map((value) => ({ value, label: this.labels().statuses[value] })),
  );
}
```

```typescript title="ui/customer-form-dialog.ts"
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  Injector,
  afterNextRender,
  computed,
  effect,
  inject,
  input,
  model,
  output,
  untracked,
  viewChild,
} from '@angular/core';
import {
  FormControl,
  FormGroup,
  FormGroupDirective,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { Button } from '@vigdx/ui/button';
import { VigValueAccessor, focusFirstInvalid } from '@vigdx/ui/core';
import { Dialog } from '@vigdx/ui/dialog';
import { InputField } from '@vigdx/ui/input-field';
import { Message } from '@vigdx/ui/message';
import { RadioGroup } from '@vigdx/ui/radio-group';
import { type SelectOption } from '@vigdx/ui/select';

import {
  CUSTOMER_STATUSES,
  type Customer,
  type CustomerDraft,
  type CustomerStatus,
} from '../data-access/customer';

export interface CustomerFormLabels {
  createTitle: string;
  editTitle: string;
  name: string;
  email: string;
  emailHint: string;
  company: string;
  status: string;
  statuses: Record<CustomerStatus, string>;
  cancel: string;
  create: string;
  save: string;
}

export const CUSTOMER_FORM_LABELS: CustomerFormLabels = {
  createTitle: 'New customer',
  editTitle: 'Edit customer',
  name: 'Name',
  email: 'Email',
  emailHint: 'Invoices and notices go to this address.',
  company: 'Company',
  status: 'Status',
  statuses: { active: 'Active', lead: 'Lead', inactive: 'Inactive' },
  cancel: 'Cancel',
  create: 'Create customer',
  save: 'Save changes',
};

const EMPTY_DRAFT: CustomerDraft = { name: '', email: '', company: '', status: 'lead' };

/**
 * Create and edit dialog of the customer list: a Reactive Form bridged to the
 * kit fields with `VigValueAccessor`. Emits a valid draft through `save`; the
 * parent persists it and closes the dialog (`open`) once that succeeded, or
 * passes `error` to show why it did not.
 */
@Component({
  selector: 'app-customer-form-dialog',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReactiveFormsModule, Button, Dialog, InputField, Message, RadioGroup, VigValueAccessor],
  template: `
    <vig-dialog [(open)]="open" [heading]="title()" width="30rem">
      <form #formRef class="flex flex-col gap-4 pt-1" [formGroup]="form" (ngSubmit)="submit()">
        @if (error(); as message) {
          <vig-message variant="error" [text]="message" />
        }
        <vig-input
          formControlName="name"
          autocomplete="off"
          [label]="labels().name"
          [maxLength]="80"
        />
        <vig-input
          formControlName="email"
          type="email"
          autocomplete="off"
          [label]="labels().email"
          [hint]="labels().emailHint"
        />
        <vig-input formControlName="company" autocomplete="off" [label]="labels().company" />
        <vig-radio-group
          formControlName="status"
          orientation="horizontal"
          [label]="labels().status"
          [options]="statusOptions()"
        />
        <div class="flex justify-end gap-2 pt-2">
          <vig-button
            variant="secondary"
            [label]="labels().cancel"
            [disabled]="saving()"
            (click)="open.set(false)"
          />
          <vig-button
            type="submit"
            [label]="customer() ? labels().save : labels().create"
            [loading]="saving()"
          />
        </div>
      </form>
    </vig-dialog>
  `,
})
export class CustomerFormDialog {
  private readonly injector = inject(Injector);

  /** Two-way: the parent opens the dialog and closes it after a successful save. */
  readonly open = model(false);
  /** The customer to edit; `null` creates a new one. */
  readonly customer = input<Customer | null>(null);
  readonly saving = input(false);
  /** Why the last save failed, shown above the fields. */
  readonly error = input<string | null>(null);
  readonly labels = input(CUSTOMER_FORM_LABELS);

  readonly save = output<CustomerDraft>();

  protected readonly form = new FormGroup({
    name: new FormControl('', {
      nonNullable: true,
      validators: [Validators.required, Validators.maxLength(80)],
    }),
    email: new FormControl('', {
      nonNullable: true,
      validators: [Validators.required, Validators.email],
    }),
    company: new FormControl('', { nonNullable: true }),
    status: new FormControl<CustomerStatus>('lead', {
      nonNullable: true,
      validators: [Validators.required],
    }),
  });

  protected readonly title = computed(() =>
    this.customer() ? this.labels().editTitle : this.labels().createTitle,
  );
  protected readonly statusOptions = computed<SelectOption<CustomerStatus>[]>(() =>
    CUSTOMER_STATUSES.map((value) => ({ value, label: this.labels().statuses[value] })),
  );

  private readonly formDirective = viewChild(FormGroupDirective);
  private readonly formRef = viewChild.required<ElementRef<HTMLFormElement>>('formRef');

  constructor() {
    // Every opening starts from the customer's values (or a blank draft),
    // with no errors from a previous attempt: `resetForm` also clears
    // the form's submitted flag.
    effect(() => {
      if (!this.open()) return;
      const customer = this.customer();
      untracked(() => {
        const draft: CustomerDraft = customer
          ? {
              name: customer.name,
              email: customer.email,
              company: customer.company,
              status: customer.status,
            }
          : EMPTY_DRAFT;
        const directive = this.formDirective();
        if (directive?.form) directive.resetForm(draft);
        else this.form.reset(draft);
      });
    });
  }

  protected submit(): void {
    if (this.saving()) return;
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      // Wait for the fields to render their error state, then focus the first.
      afterNextRender(() => focusFirstInvalid(this.formRef()), { injector: this.injector });
      return;
    }
    this.save.emit(this.form.getRawValue());
  }
}
```

```typescript title="ui/customer-table.ts"
import { DatePipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { Badge, type BadgeVariant } from '@vigdx/ui/badge';
import { Button, ButtonIcon } from '@vigdx/ui/button';
import { EmptyState, EmptyStateActions } from '@vigdx/ui/empty-state';
import { Icon } from '@vigdx/ui/icon';
import { Menu, type MenuEntry, MenuTrigger } from '@vigdx/ui/menu';
import {
  Table,
  TableCell,
  TableColumn,
  TableEmpty,
  type TableLazyLoadEvent,
  type TableSort,
} from '@vigdx/ui/table';

import type {
  Customer,
  CustomerQuery,
  CustomerSort,
  CustomerSortField,
  CustomerStatus,
} from '../data-access/customer';

export interface CustomerTableLabels {
  caption: string;
  name: string;
  email: string;
  company: string;
  status: string;
  created: string;
  actions: string;
  /** Name of a row's action button; `{0}` is the customer name. */
  actionsFor: string;
  edit: string;
  delete: string;
  statuses: Record<CustomerStatus, string>;
  emptyTitle: string;
  emptyDescription: string;
  create: string;
  noMatchesTitle: string;
  noMatchesDescription: string;
  clearFilters: string;
  errorTitle: string;
  /** Shown under `errorTitle`; never the technical error, which stays out of the UI. */
  errorDescription: string;
  retry: string;
}

export const CUSTOMER_TABLE_LABELS: CustomerTableLabels = {
  caption: 'Customers',
  name: 'Name',
  email: 'Email',
  company: 'Company',
  status: 'Status',
  created: 'Created',
  actions: 'Actions',
  actionsFor: 'Actions for {0}',
  edit: 'Edit',
  delete: 'Delete',
  statuses: { active: 'Active', lead: 'Lead', inactive: 'Inactive' },
  emptyTitle: 'No customers yet',
  emptyDescription: 'Customers you add are listed here.',
  create: 'New customer',
  noMatchesTitle: 'No matching customers',
  noMatchesDescription: 'Try another search or status.',
  clearFilters: 'Clear filters',
  errorTitle: 'Customers could not be loaded',
  errorDescription: 'Check your connection and try again.',
  retry: 'Try again',
};

const STATUS_VARIANTS: Record<CustomerStatus, BadgeVariant> = {
  active: 'success',
  lead: 'info',
  inactive: 'secondary',
};

const SORT_FIELDS: readonly string[] = ['name', 'company', 'status', 'createdAt'];

/** The table's sort, narrowed to the columns the server sorts by. */
function toCustomerSort(sort: TableSort | null): CustomerSort | null {
  return sort && SORT_FIELDS.includes(sort.field)
    ? { field: sort.field as CustomerSortField, direction: sort.direction }
    : null;
}

/**
 * The customers table in lazy mode: the server pages and sorts, the table
 * reports every paging or sorting change through `pageChange`. Shows the
 * loading, empty, no-match and error states. Presentational: inputs in,
 * outputs out.
 */
@Component({
  selector: 'app-customer-table',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    DatePipe,
    Badge,
    Button,
    ButtonIcon,
    EmptyState,
    EmptyStateActions,
    Icon,
    Menu,
    MenuTrigger,
    Table,
    TableCell,
    TableColumn,
    TableEmpty,
  ],
  template: `
    <vig-table
      [caption]="labels().caption"
      [items]="customers()"
      [rowId]="rowId"
      [lazy]="true"
      [totalRecords]="total()"
      [loading]="loading()"
      [paginator]="true"
      [first]="query().first"
      [rows]="query().rows"
      [rowsPerPageOptions]="rowsPerPageOptions"
      [sort]="query().sort"
      (lazyLoad)="onLazyLoad($event)"
    >
      <vig-col field="name" [header]="labels().name" [sortable]="true" [rowHeader]="true" />
      <vig-col field="email" [header]="labels().email" />
      <vig-col field="company" [header]="labels().company" [sortable]="true" />
      <vig-col field="status" [header]="labels().status" [sortable]="true">
        <ng-template vigTableCell let-row>
          <vig-badge [label]="labels().statuses[status(row)]" [variant]="statusVariant(row)" />
        </ng-template>
      </vig-col>
      <vig-col field="createdAt" [header]="labels().created" [sortable]="true">
        <ng-template vigTableCell let-row>
          {{ createdAt(row) | date: 'mediumDate' : 'UTC' }}
        </ng-template>
      </vig-col>
      <vig-col [header]="labels().actions" align="end" width="5rem">
        <ng-template vigTableCell let-row>
          <vig-menu [items]="rowActions().get(row.id) ?? []">
            <vig-button
              vigMenuTrigger
              appearance="text"
              variant="secondary"
              size="sm"
              [ariaLabel]="actionsLabel(row)"
            >
              <vig-icon vigButtonIcon name="more-horizontal" />
            </vig-button>
          </vig-menu>
        </ng-template>
      </vig-col>

      <ng-template vigTableEmpty>
        @if (error()) {
          <vig-empty-state
            size="sm"
            icon="error"
            [headingLevel]="2"
            [heading]="labels().errorTitle"
            [description]="labels().errorDescription"
          >
            <div vigEmptyStateActions class="contents">
              <vig-button size="sm" [label]="labels().retry" (click)="retry.emit()" />
            </div>
          </vig-empty-state>
        } @else if (!loading()) {
          @if (filtered()) {
            <vig-empty-state
              size="sm"
              icon="search"
              [headingLevel]="2"
              [heading]="labels().noMatchesTitle"
              [description]="labels().noMatchesDescription"
            >
              <div vigEmptyStateActions class="contents">
                <vig-button
                  size="sm"
                  variant="secondary"
                  [label]="labels().clearFilters"
                  (click)="clearFilters.emit()"
                />
              </div>
            </vig-empty-state>
          } @else {
            <vig-empty-state
              size="sm"
              icon="inbox"
              [headingLevel]="2"
              [heading]="labels().emptyTitle"
              [description]="labels().emptyDescription"
            >
              <div vigEmptyStateActions class="contents">
                <vig-button size="sm" [label]="labels().create" (click)="create.emit()" />
              </div>
            </vig-empty-state>
          }
        }
      </ng-template>
    </vig-table>
  `,
})
export class CustomerTable {
  readonly customers = input.required<readonly Customer[]>();
  readonly total = input.required<number>();
  readonly query = input.required<CustomerQuery>();
  readonly loading = input(false);
  readonly error = input<Error | undefined>(undefined);
  /** Whether a search or status filter is active (picks the empty state). */
  readonly filtered = input(false);
  readonly labels = input(CUSTOMER_TABLE_LABELS);

  readonly pageChange = output<{ first: number; rows: number; sort: CustomerSort | null }>();
  readonly edit = output<Customer>();
  readonly remove = output<Customer>();
  readonly create = output<void>();
  readonly retry = output<void>();
  readonly clearFilters = output<void>();

  protected readonly rowsPerPageOptions = [10, 25, 50];
  protected readonly rowId = (customer: Customer) => customer.id;

  /** Menu entries per row, rebuilt only when the rows or labels change. */
  protected readonly rowActions = computed(
    () =>
      new Map(
        this.customers().map((customer): [string, MenuEntry[]] => [
          customer.id,
          [
            { label: this.labels().edit, command: () => this.edit.emit(customer) },
            'separator',
            {
              label: this.labels().delete,
              danger: true,
              command: () => this.remove.emit(customer),
            },
          ],
        ]),
      ),
  );

  protected onLazyLoad(event: TableLazyLoadEvent): void {
    this.pageChange.emit({
      first: event.first,
      rows: event.rows,
      sort: toCustomerSort(event.sort),
    });
  }

  // Cell templates receive untyped rows; these keep the template type-safe.
  protected status(row: Customer): CustomerStatus {
    return row.status;
  }

  protected statusVariant(row: Customer): BadgeVariant {
    return STATUS_VARIANTS[row.status];
  }

  protected createdAt(row: Customer): string {
    return row.createdAt;
  }

  protected actionsLabel(row: Customer): string {
    return this.labels().actionsFor.replace('{0}', row.name);
  }
}
```

```typescript title="ui/customer-table.spec.ts"
import { provideZonelessChangeDetection } from '@angular/core';
import { type ComponentFixture, TestBed } from '@angular/core/testing';
import { provideVigdxUi } from '@vigdx/ui/core';

import type { Customer, CustomerQuery } from '../data-access/customer';
import { CUSTOMER_TABLE_LABELS, CustomerTable } from './customer-table';

const ADA: Customer = {
  id: 'C-1',
  name: 'Ada Lovelace',
  email: 'ada@example.com',
  company: 'Analytical',
  status: 'lead',
  createdAt: '2026-03-15',
};

const QUERY: CustomerQuery = { first: 0, rows: 10, sort: null, search: '', status: null };

describe('CustomerTable', () => {
  let fixture: ComponentFixture<CustomerTable>;
  let el: HTMLElement;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      providers: [provideZonelessChangeDetection(), provideVigdxUi()],
    });
    fixture = TestBed.createComponent(CustomerTable);
    fixture.componentRef.setInput('customers', [ADA]);
    fixture.componentRef.setInput('total', 1);
    fixture.componentRef.setInput('query', QUERY);
    el = fixture.nativeElement;
    await fixture.whenStable();
  });

  async function set(inputs: Record<string, unknown>): Promise<void> {
    for (const [name, value] of Object.entries(inputs)) fixture.componentRef.setInput(name, value);
    await fixture.whenStable();
  }

  const button = (name: string) =>
    Array.from(el.querySelectorAll('button')).find((b) => b.textContent?.includes(name));

  it('renders rows with a row header, a status badge, the calendar date and a named action button', () => {
    expect(el.querySelector('caption')?.textContent).toContain('Customers');
    expect(el.querySelector('tbody th[scope="row"]')?.textContent?.trim()).toBe('Ada Lovelace');
    expect(el.querySelector('tbody vig-badge')?.textContent).toContain('Lead');
    expect(el.querySelector('tbody')?.textContent).toContain('Mar 15, 2026');
    expect(el.querySelector('button[aria-label="Actions for Ada Lovelace"]')).not.toBeNull();
  });

  it('reports paging and narrows the sort to server-sortable columns', async () => {
    const pages: unknown[] = [];
    fixture.componentInstance.pageChange.subscribe((page) => pages.push(page));
    await set({ total: 30 });

    el.querySelector<HTMLButtonElement>('th button')?.click();
    await fixture.whenStable();
    expect(pages[pages.length - 1]).toEqual({
      first: 0,
      rows: 10,
      sort: { field: 'name', direction: 'asc' },
    });

    el.querySelector<HTMLButtonElement>('button[aria-label="Next page"]')?.click();
    await fixture.whenStable();
    expect(pages[pages.length - 1]).toMatchObject({ first: 10, rows: 10 });
  });

  it('picks the empty, no-match and error states', async () => {
    const created = vi.fn();
    const cleared = vi.fn();
    const retried = vi.fn();
    fixture.componentInstance.create.subscribe(created);
    fixture.componentInstance.clearFilters.subscribe(cleared);
    fixture.componentInstance.retry.subscribe(retried);

    await set({ customers: [], total: 0 });
    expect(el.textContent).toContain('No customers yet');
    button('New customer')?.click();
    expect(created).toHaveBeenCalled();

    await set({ filtered: true });
    expect(el.textContent).toContain('No matching customers');
    button('Clear filters')?.click();
    expect(cleared).toHaveBeenCalled();

    await set({ error: new Error('offline') });
    expect(el.textContent).toContain('Customers could not be loaded');
    expect(el.textContent).toContain('Check your connection and try again.');
    // The technical message stays out of the UI.
    expect(el.textContent).not.toContain('offline');
    button('Try again')?.click();
    expect(retried).toHaveBeenCalled();
  });

  it('shows no empty state while the first page loads', async () => {
    await set({ customers: [], total: 0, loading: true });
    expect(el.querySelector('vig-empty-state')).toBeNull();
  });

  it('takes translated labels', async () => {
    await set({ labels: { ...CUSTOMER_TABLE_LABELS, actionsFor: 'Aktionen für {0}' } });
    expect(el.querySelector('button[aria-label="Aktionen für Ada Lovelace"]')).not.toBeNull();
  });
});
```
