Form page
vig-card s, every field type, cross-field validation, an unsaved-changes guard with the Confirm service and a pending submit state, written in Reactive Forms, with the same form in Signal Forms.
Live demo
New project
Signal Forms variant
form() and [formField] from @angular/forms/signals : same inputs, outputs and rules, no VigValueAccessor . Submit it to see the validation; a valid draft is announced in a toast.
A routed page that creates and edits one record: /projects/new and /projects/:id . The form is split into sections, uses every common field type, validates across fields, protects unsaved changes and shows its submit state. It is written in Reactive Forms; the same form in Signal Forms sits next to it with the same contract, so pick the forms API your app uses.
When to use
- Creating or editing a record that needs more room than a dialog: several sections, long text, dates, money.
- The record has its own URL (deep links, back button, opening in a new tab).
- Users may leave half-way, so unsaved changes need protection.
- For three or four fields edited next to a list, use the dialog of the
crud-listrecipe instead.
Component choices
| Need | Component | Why | Alternatives |
|---|---|---|---|
| Sections | vig-card with heading and headingLevel 2 | Real headings structure the page for screen readers and the outline | vig-accordion for optional sections; vig-stepper for a guided multi-step flow |
| Text | vig-input ( maxLength , autocomplete ) | Label, hint, error and counter wiring built in | vig-autocomplete when the value comes from a list |
| Long text | vig-input with multiline and autoResize | Grows with the content instead of scrolling inside a box | — |
| Money | vig-number-input with currency | Locale-aware parsing and formatting, null when empty | Plain vig-input for codes that only look numeric (postal codes, IDs) |
| Choice of many | vig-select with filter | Six or more options, searchable | vig-autocomplete for remote search |
| Choice of a few | vig-radio-group horizontal | Two to five options visible at once, native radios | vig-select-button for a compact segmented look |
| Dates | vig-date-picker ( clearable for optional ones) | Calendar plus typing, a local-midnight Date | Two pickers rather than a range picker when each end has its own rules |
| On/off setting | vig-toggle-switch with hint | Immediate, binary, explains its effect | vig-checkbox for consent and agreement |
| Leaving with changes | CanDeactivate guard + Confirm service | The kit's confirmation dialog; works for every navigation in the app | beforeunload (also used) only covers closing the tab |
| Feedback | Toast service | Success and failure without moving focus | vig-message above the form for errors that block the user |
Folder structure
Angular CLI
src/app/features/projects/
data-access/
project.ts domain types and the date rule (endsBeforeStart)
projects-api.ts abstract API = DI token, ProjectNotFoundError
http-projects-api.ts HttpClient implementation (404 → ProjectNotFoundError)
in-memory-projects-api.ts seeded fake for demos and tests
project-store.ts signal store: open project, clients, saving
feature/
project-form-page.ts routed smart page
unsaved-changes-guard.ts reusable CanDeactivate guard
projects.routes.ts /new and /:id
ui/
project-form-model.ts form value type, mapping and labels
project-form.ts Reactive Forms variant
project-signal-form.ts Signal Forms variant Wire it into src/app/app.routes.ts ; withComponentInputBinding() in provideRouter passes :id to the page's id input:
{
path: 'projects',
providers: [{ provide: ProjectsApi, useClass: HttpProjectsApi }],
loadChildren: () =>
import('./features/projects/feature/projects.routes').then((m) => m.projectsRoutes),
}Nx
npx nx g @nx/angular:library --directory=libs/projects/data-access --name=projects-data-access --tags=type:data-access,scope:projects --prefix=app --no-interactive
npx nx g @nx/angular:library --directory=libs/projects/feature-form --name=projects-feature-form --tags=type:feature,scope:projects --prefix=app --no-interactive
npx nx g @nx/angular:library --directory=libs/projects/ui --name=projects-ui --tags=type:ui,scope:projects --prefix=app --no-interactive The guard is not specific to projects: once a second feature needs it, move it to a libs/shared/util-routing library ( type:util , scope:shared ).
Key decisions
- One page for create and edit. The
idinput decides:new(or none) opens a blank form, an id loads the project. After a create the page navigates to the new project's URL withreplaceUrl, so the back button does not return to an empty form; an edit replaces the loaded project in the store without a refetch. - The form is presentational.
ProjectFormtakes the project and the client options as inputs and emits a validProjectDraft; the page saves it. Changing theprojectinput resets the form, which also makes the saved values the new baseline. The page readsisDirty()for the guard. - Cross-field rules sit on the field to fix. "End date before start date" is a domain function in
project.ts; in Reactive Forms it is a validator on the end date that reads the sibling and re-runs when the start date changes. "Billable projects need a budget" adds or removesValidators.requiredon the budget wheneverbillablechanges, so the field also gets the required marker andaria-required. The errors show under the end date (or budget), andfocusFirstInvalidlands there. A group-level validator would leave no field marked invalid. In Signal Forms,validate()withvalueOf()andrequired()withwhenexpress the same rules in the schema. - Dates are calendar days. The pickers work with local-midnight
Dates; the API getsYYYY-MM-DDstrings through the kit'stoIsoDateandparseIsoDate, so no time zone shifts the day. - `errorDisplay` stays `'touched'`. Errors appear once a field is left, and every field is marked touched on a failed submit. A long form whose users tab through it first may prefer
provideVigdxUi({ errorDisplay: 'interacted' })(errors after an edit or a submit): the Reactive variant supports it as is, becauseVigValueAccessormirrors the form's submitted flag; the Signal Forms variant submits through[formRoot], whose<form>submit event the fields follow. - Reactive or Signal Forms. Both are stable in Angular 22 and the kit supports both. Reactive Forms needs
VigValueAccessornext to the fields andvalueChangessubscriptions for dependent rules; Signal Forms keeps the model in a signal, binds with[formField]and re-evaluates rules automatically. Use the one the rest of the app uses. - Submit state. The submit button shows
loadingwhile saving and a second submit is ignored; the button is never disabled up front, so users can always submit and learn what is missing.
Accessibility
- The form is named by the page heading (
aria-labelledby), each card title is anh2, and every field has a visible label; required fields carry the kit's required marker. - A failed submit moves focus to the first invalid field; its error is linked with
aria-describedbyand announced once. - The guard's confirmation offers "Keep editing" as the safe choice; the native dialog returns focus to the link that was followed.
- Loading shows skeletons inside a
role="status"container with a name; not found and load errors usevig-empty-stateheadings, with a retry for errors; their texts are user-facing constants inPROJECT_FORM_PAGE_TEXT, never the technicalerror.message. - Radio buttons are native, so arrow keys and the single tab stop come from the browser.
Performance
- The page and its forms are lazy-loaded with the feature routes;
@angular/forms/signalsis only in the bundle when the Signal Forms variant is used. OnPusheverywhere; options lists arecomputed, so they are rebuilt only when their input changes.- The client list loads once per page visit, in parallel with the project.
Definition of done
nx build <app>(orng build) succeeds; strict templates accept the[formField]bindings if you use Signal Forms.nx lintpasses, including module boundaries.- The specs pass: load for edit, not found, invalid submit focuses the first error, both cross-field rules, create navigates to the new URL, edit saves without a refetch, a failed save keeps the input, the guard asks only with unsaved changes.
- axe reports no violations with errors showing, in light and dark mode.
- Keyboard only: fill every field, submit, fix the errors, save, then edit and leave with changes.
Source files
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { type Observable, catchError, throwError } from 'rxjs';
import type { Client, Project, ProjectDraft } from './project';
import { ProjectNotFoundError, type ProjectsApi } from './projects-api';
/** Base URLs of the backend; adapt them to yours. */
export const PROJECTS_URL = '/api/projects';
export const CLIENTS_URL = '/api/clients';
/** `ProjectsApi` over HTTP. Needs `provideHttpClient()` in the application config. */
@Injectable()
export class HttpProjectsApi implements ProjectsApi {
private readonly http = inject(HttpClient);
get(id: string): Observable<Project> {
return this.http
.get<Project>(`${PROJECTS_URL}/${encodeURIComponent(id)}`)
.pipe(
catchError((error: unknown) =>
throwError(() =>
error instanceof HttpErrorResponse && error.status === 404
? new ProjectNotFoundError(id)
: error,
),
),
);
}
create(draft: ProjectDraft): Observable<Project> {
return this.http.post<Project>(PROJECTS_URL, draft);
}
update(id: string, draft: ProjectDraft): Observable<Project> {
return this.http.put<Project>(`${PROJECTS_URL}/${encodeURIComponent(id)}`, draft);
}
clients(): Observable<Client[]> {
return this.http.get<Client[]>(CLIENTS_URL);
}
}
import { Injectable, InjectionToken, inject, signal } from '@angular/core';
import { type Observable, map, timer } from 'rxjs';
import type { Client, Project, ProjectDraft } from './project';
import { ProjectNotFoundError, type ProjectsApi } from './projects-api';
/** Simulated network latency of `InMemoryProjectsApi` in ms; tests set 0. */
export const PROJECTS_API_LATENCY = new InjectionToken<number>('PROJECTS_API_LATENCY', {
factory: () => 400,
});
const CLIENTS: Client[] = [
{ id: 'northwind', name: 'Northwind Traders' },
{ id: 'contoso', name: 'Contoso' },
{ id: 'fabrikam', name: 'Fabrikam' },
{ id: 'tailspin', name: 'Tailspin Toys' },
{ id: 'wingtip', name: 'Wingtip Toys' },
];
const PROJECTS: Project[] = [
{
id: 'P-1001',
name: 'Website relaunch',
clientId: 'northwind',
priority: 'high',
startDate: '2026-03-02',
endDate: '2026-06-30',
budget: 48000,
billable: true,
description: 'New information architecture, design system and CMS migration.',
},
{
id: 'P-1002',
name: 'Support portal',
clientId: 'contoso',
priority: 'medium',
startDate: '2026-05-04',
endDate: null,
budget: null,
billable: false,
description: '',
},
];
/**
* `ProjectsApi` over an in-memory list with simulated latency, for demos,
* prototypes and tests. Deterministic: fixed seed, sequential ids.
*/
@Injectable()
export class InMemoryProjectsApi implements ProjectsApi {
private readonly latency = inject(PROJECTS_API_LATENCY);
private projects = PROJECTS.map((project) => ({ ...project }));
private nextId = 1003;
/** When true every request fails, to exercise the error states. */
readonly failing = signal(false);
get(id: string): Observable<Project> {
return this.respond(() => {
const project = this.projects.find((candidate) => candidate.id === id);
if (!project) throw new ProjectNotFoundError(id);
return { ...project };
});
}
create(draft: ProjectDraft): Observable<Project> {
return this.respond(() => {
const project = { ...draft, id: `P-${this.nextId++}` };
this.projects = [...this.projects, project];
return { ...project };
});
}
update(id: string, draft: ProjectDraft): Observable<Project> {
return this.respond(() => {
if (!this.projects.some((project) => project.id === id)) throw new ProjectNotFoundError(id);
const project = { ...draft, id };
this.projects = this.projects.map((candidate) => (candidate.id === id ? project : candidate));
return { ...project };
});
}
clients(): Observable<Client[]> {
return this.respond(() => CLIENTS.map((client) => ({ ...client })));
}
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();
}),
);
}
}
import { Injectable, type Signal, computed, inject, signal } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';
import { firstValueFrom } from 'rxjs';
import type { Project, ProjectDraft } from './project';
import { ProjectNotFoundError, ProjectsApi } from './projects-api';
/**
* State of the project form page: which project is open (none while
* creating), the project and the client options as loaded, and saving.
* Provided by the page component.
*/
@Injectable()
export class ProjectStore {
private readonly api = inject(ProjectsApi);
/** Where the open project's id comes from; see {@link connect}. */
private readonly source = signal<Signal<string | null>>(signal(null));
/** The open project's id; `null` while creating a new one. */
private readonly id = computed(() => this.source()());
readonly isNew = computed(() => this.id() === null);
// `id` hands a server-rendered value to the browser in the transfer state:
// hydration starts from it instead of loading again, so the page keeps the
// server's form rather than flashing back to its loading state.
private readonly projectResource = rxResource({
id: 'project-store.project',
// `undefined` params keep the resource idle: nothing to load for a new project.
params: () => this.id() ?? undefined,
stream: ({ params }) => this.api.get(params),
});
private readonly clientsResource = rxResource({
id: 'project-store.clients',
stream: () => this.api.clients(),
});
/** The loaded (or last saved) project; `null` while creating. */
readonly project = computed<Project | null>(() =>
this.projectResource.hasValue() ? this.projectResource.value() : null,
);
readonly clients = computed(() =>
this.clientsResource.hasValue() ? this.clientsResource.value() : [],
);
readonly loading = computed(
() => this.projectResource.isLoading() || this.clientsResource.isLoading(),
);
readonly error = computed(() => this.projectResource.error() ?? this.clientsResource.error());
readonly notFound = computed(() => this.projectResource.error() instanceof ProjectNotFoundError);
private readonly savingSignal = signal(false);
readonly saving = this.savingSignal.asReadonly();
/**
* Follows the open project's id — `null` for a blank one — from a signal
* the page owns (its route parameter), so the store derives what to load
* instead of being told after every change.
*/
connect(id: Signal<string | null>): void {
this.source.set(id);
}
reload(): void {
this.projectResource.reload();
this.clientsResource.reload();
}
/**
* Creates or updates the open project. An updated project replaces the
* loaded one without a refetch; after a create the page navigates to the
* new project's URL, which opens it.
*/
async save(draft: ProjectDraft): Promise<Project> {
const id = this.id();
this.savingSignal.set(true);
try {
const saved = await firstValueFrom(id ? this.api.update(id, draft) : this.api.create(draft));
if (id) this.projectResource.set(saved);
return saved;
} finally {
this.savingSignal.set(false);
}
}
}
import {
ApplicationRef,
TransferState,
makeStateKey,
provideZonelessChangeDetection,
signal,
} from '@angular/core';
import { provideClientHydration } from '@angular/platform-browser';
import { TestBed } from '@angular/core/testing';
import { InMemoryProjectsApi, PROJECTS_API_LATENCY } from './in-memory-projects-api';
import type { Client, Project, ProjectDraft } from './project';
import { ProjectStore } from './project-store';
import { ProjectsApi } from './projects-api';
const DRAFT: ProjectDraft = {
name: 'Mobile app',
clientId: 'contoso',
priority: 'low',
startDate: '2026-07-01',
endDate: null,
budget: null,
billable: false,
description: '',
};
describe('ProjectStore', () => {
let store: ProjectStore;
let api: InMemoryProjectsApi;
/** Stands in for the page's route parameter. */
const id = signal<string | null>(null);
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
ProjectStore,
InMemoryProjectsApi,
{ provide: ProjectsApi, useExisting: InMemoryProjectsApi },
{ provide: PROJECTS_API_LATENCY, useValue: 0 },
],
});
store = TestBed.inject(ProjectStore);
api = TestBed.inject(InMemoryProjectsApi);
id.set(null);
store.connect(id);
});
async function settle(): Promise<void> {
for (let i = 0; i < 2; i++) {
await new Promise((resolve) => setTimeout(resolve));
await TestBed.inject(ApplicationRef).whenStable();
}
}
it('starts blank and loads the client options', async () => {
await settle();
expect(store.isNew()).toBe(true);
expect(store.project()).toBeNull();
expect(store.clients().map((c) => c.id)).toContain('northwind');
expect(store.loading()).toBe(false);
});
it('follows the connected id and flags unknown ids as not found', async () => {
id.set('P-1001');
await settle();
expect(store.project()?.name).toBe('Website relaunch');
id.set('P-0');
await settle();
expect(store.notFound()).toBe(true);
expect(store.project()).toBeNull();
});
it('creates without opening, and updates in place without a refetch', async () => {
await settle();
const created = await store.save(DRAFT);
expect(created.id).toBe('P-1003');
expect(store.isNew()).toBe(true);
id.set(created.id);
await settle();
const get = vi.spyOn(api, 'get');
const updated = await store.save({ ...DRAFT, name: 'Mobile app v2' });
await settle();
expect(store.project()).toEqual(updated);
expect(get).not.toHaveBeenCalled();
expect(store.saving()).toBe(false);
});
it('surfaces load errors and retries', async () => {
api.failing.set(true);
id.set('P-1001');
await settle();
expect(store.error()?.message).toBe('The server is not responding.');
expect(store.notFound()).toBe(false);
api.failing.set(false);
store.reload();
await settle();
expect(store.error()).toBeUndefined();
expect(store.project()?.id).toBe('P-1001');
});
it('hydrates from what the server rendered, without loading again', async () => {
// What the server put in the page: the project and the clients it loaded.
const server = await firstServerRender();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideClientHydration(),
ProjectStore,
InMemoryProjectsApi,
{ provide: ProjectsApi, useExisting: InMemoryProjectsApi },
{ provide: PROJECTS_API_LATENCY, useValue: 0 },
],
});
const state = TestBed.inject(TransferState);
state.set(makeStateKey<Project | null>('project-store.project'), server.project);
state.set(makeStateKey<Client[]>('project-store.clients'), server.clients);
const client = TestBed.inject(ProjectStore);
const clientApi = TestBed.inject(InMemoryProjectsApi);
const get = vi.spyOn(clientApi, 'get');
const clients = vi.spyOn(clientApi, 'clients');
client.connect(signal('P-1001'));
// The first render already has the form's data: no loading state to flash.
expect(client.loading()).toBe(false);
expect(client.project()?.name).toBe('Website relaunch');
expect(client.clients().length).toBe(server.clients.length);
await settle();
expect(get).not.toHaveBeenCalled();
expect(clients).not.toHaveBeenCalled();
});
async function firstServerRender() {
id.set('P-1001');
await settle();
return { project: store.project(), clients: store.clients() };
}
});
export type ProjectPriority = 'low' | 'medium' | 'high';
export const PROJECT_PRIORITIES: readonly ProjectPriority[] = ['low', 'medium', 'high'];
export interface Project {
id: string;
name: string;
clientId: string;
priority: ProjectPriority;
/** Calendar dates as `YYYY-MM-DD`; `endDate` is open-ended when null. */
startDate: string;
endDate: string | null;
/** Budget in euros; required for billable projects. */
budget: number | null;
billable: boolean;
description: string;
}
/** What the form submits; the server owns the `id`. */
export type ProjectDraft = Omit<Project, 'id'>;
export interface Client {
id: string;
name: string;
}
export const NAME_MAX_LENGTH = 80;
export const DESCRIPTION_MAX_LENGTH = 500;
/**
* Domain rule shared by both form variants: a project cannot end before it
* starts. Compares calendar days, so the time of day never matters.
*/
export function endsBeforeStart(start: Date | null, end: Date | null): boolean {
if (!start || !end) return false;
const day = (date: Date) => date.getFullYear() * 10000 + date.getMonth() * 100 + date.getDate();
return day(end) < day(start);
}
import type { Observable } from 'rxjs';
import type { Client, Project, ProjectDraft } from './project';
/**
* The projects backend as the form page needs it; the abstract class is the
* DI token. Bind an implementation in the app or route providers:
*
* ```ts
* providers: [{ provide: ProjectsApi, useClass: HttpProjectsApi }]
* ```
*/
export abstract class ProjectsApi {
/** Errors with `ProjectNotFoundError` when there is no such project. */
abstract get(id: string): Observable<Project>;
abstract create(draft: ProjectDraft): Observable<Project>;
abstract update(id: string, draft: ProjectDraft): Observable<Project>;
/** The clients a project can belong to (the options of the client select). */
abstract clients(): Observable<Client[]>;
}
export class ProjectNotFoundError extends Error {
constructor(readonly id: string) {
super(`Project ${id} does not exist.`);
this.name = 'ProjectNotFoundError';
}
}
import {
ChangeDetectionStrategy,
Component,
DestroyRef,
computed,
inject,
input,
viewChild,
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Button } from '@vigdx/ui/button';
import { EmptyState, EmptyStateActions } from '@vigdx/ui/empty-state';
import { Skeleton } from '@vigdx/ui/skeleton';
import { Toast } from '@vigdx/ui/toast';
import type { ProjectDraft } from '../data-access/project';
import { ProjectStore } from '../data-access/project-store';
import { ProjectForm } from '../ui/project-form';
import type { HasUnsavedChanges } from './unsaved-changes-guard';
export const PROJECT_FORM_PAGE_TEXT = {
createTitle: 'New project',
editTitle: 'Edit project',
loading: 'Loading the project',
created: (name: string) => `${name} was created.`,
saved: (name: string) => `${name} was saved.`,
saveFailed: 'The project could not be saved. Your changes are still here; try again.',
notFoundTitle: 'Project not found',
notFoundDescription: 'It may have been deleted, or the link is wrong.',
errorTitle: 'The project could not be loaded',
errorDescription: 'Check your connection and try again.',
retry: 'Try again',
};
/**
* Routed create and edit page: `/projects/new` creates, `/projects/:id`
* edits. Orchestration only: opens the project in the store, renders the
* load states and the form, saves, reports the result and guards unsaved
* changes (with `unsavedChangesGuard` on its route, and on tab close).
*/
@Component({
selector: 'app-project-form-page',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [ProjectStore],
imports: [Button, EmptyState, EmptyStateActions, Skeleton, ProjectForm],
host: {
class: 'flex flex-col gap-6',
'(window:beforeunload)': 'onBeforeUnload($event)',
},
template: `
<h1 [id]="headingId" class="text-h2 text-foreground">{{ title() }}</h1>
@if (store.notFound()) {
<vig-empty-state
icon="search"
[headingLevel]="2"
[heading]="text.notFoundTitle"
[description]="text.notFoundDescription"
/>
} @else if (store.error()) {
<vig-empty-state
icon="error"
[headingLevel]="2"
[heading]="text.errorTitle"
[description]="text.errorDescription"
>
<div vigEmptyStateActions class="contents">
<vig-button [label]="text.retry" (click)="store.reload()" />
</div>
</vig-empty-state>
} @else if (store.loading()) {
<div class="flex flex-col gap-4" role="status" [attr.aria-label]="text.loading">
<vig-skeleton shape="rect" height="12rem" />
<vig-skeleton shape="rect" height="10rem" />
</div>
} @else {
<app-project-form
[project]="store.project()"
[clients]="store.clients()"
[saving]="store.saving()"
[labelledBy]="headingId"
(save)="save($event)"
/>
}
`,
})
export class ProjectFormPage implements HasUnsavedChanges {
protected readonly store = inject(ProjectStore);
private readonly toast = inject(Toast);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private destroyed = false;
/** The `:id` route parameter (component input binding); `new` or none creates. */
readonly id = input<string>();
protected readonly text = PROJECT_FORM_PAGE_TEXT;
protected readonly headingId = 'project-form-heading';
protected readonly title = computed(() =>
this.store.isNew() ? this.text.createTitle : this.text.editTitle,
);
private readonly form = viewChild(ProjectForm);
constructor() {
inject(DestroyRef).onDestroy(() => (this.destroyed = true));
this.store.connect(
computed(() => {
const id = this.id();
return !id || id === 'new' ? null : id;
}),
);
}
hasUnsavedChanges(): boolean {
return this.form()?.isDirty() ?? false;
}
/** Closing or reloading the tab with unsaved changes asks the browser's own question. */
protected onBeforeUnload(event: BeforeUnloadEvent): void {
if (this.hasUnsavedChanges()) event.preventDefault();
}
protected async save(draft: ProjectDraft): Promise<void> {
const created = this.store.isNew();
const url = this.router.url;
try {
const saved = await this.store.save(draft);
// Saved values are the new baseline: nothing left to guard.
this.form()?.reset(saved);
this.toast.success(created ? this.text.created(saved.name) : this.text.saved(saved.name));
// Continue on the new project's URL, replacing `/new` in the history, unless the
// user left while the request was running.
if (created && !this.destroyed && this.router.url === url) {
await this.router.navigate([saved.id], { relativeTo: this.route.parent, replaceUrl: true });
}
} catch {
this.toast.error(this.text.saveFailed);
}
}
}
import { ApplicationRef, Component, provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import type { FormGroup } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { Router, provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { Subject } from 'rxjs';
import { Confirm } from '@vigdx/ui/confirm-dialog';
import { provideVigdxUi } from '@vigdx/ui/core';
import { Toast } from '@vigdx/ui/toast';
import { InMemoryProjectsApi, PROJECTS_API_LATENCY } from '../data-access/in-memory-projects-api';
import type { Project } from '../data-access/project';
import { ProjectsApi } from '../data-access/projects-api';
import { ProjectForm } from '../ui/project-form';
import { ProjectFormPage } from './project-form-page';
import { projectsRoutes } from './projects.routes';
@Component({ template: 'Elsewhere' })
class Elsewhere {}
describe('ProjectFormPage', () => {
const confirm = { ask: vi.fn() };
const toast = { success: vi.fn(), error: vi.fn() };
let harness: RouterTestingHarness;
let api: InMemoryProjectsApi;
beforeEach(async () => {
confirm.ask.mockReset();
toast.success.mockReset();
toast.error.mockReset();
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideVigdxUi(),
provideRouter(
[
{ path: 'projects', children: projectsRoutes },
{ path: 'elsewhere', component: Elsewhere },
],
withComponentInputBinding(),
),
InMemoryProjectsApi,
{ provide: ProjectsApi, useExisting: InMemoryProjectsApi },
{ provide: PROJECTS_API_LATENCY, useValue: 0 },
{ provide: Confirm, useValue: confirm },
{ provide: Toast, useValue: toast },
],
});
api = TestBed.inject(InMemoryProjectsApi);
harness = await RouterTestingHarness.create();
});
async function settle(): Promise<void> {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) => setTimeout(resolve));
await TestBed.inject(ApplicationRef).whenStable();
}
}
async function open(url: string): Promise<HTMLElement> {
await harness.navigateByUrl(url);
await settle();
return harness.routeNativeElement as HTMLElement;
}
const formGroup = () =>
(
harness.fixture.debugElement.query(By.directive(ProjectForm))
.componentInstance as unknown as {
form: FormGroup;
}
).form;
const input = (el: HTMLElement, label: string) =>
Array.from(el.querySelectorAll<HTMLInputElement>('vig-input input, vig-input textarea')).find(
(field) => field.closest('vig-input')?.textContent?.includes(label),
) as HTMLInputElement;
function type(field: HTMLInputElement, value: string): void {
field.value = value;
field.dispatchEvent(new Event('input'));
field.dispatchEvent(new Event('blur'));
}
async function submit(el: HTMLElement): Promise<void> {
el.querySelector('form')?.dispatchEvent(new Event('submit'));
await settle();
}
it('opens an existing project for editing', async () => {
const el = await open('/projects/P-1001');
expect(el.querySelector('h1')?.textContent).toContain('Edit project');
expect(input(el, 'Project name').value).toBe('Website relaunch');
expect(formGroup().getRawValue()).toMatchObject({
clientId: 'northwind',
priority: 'high',
billable: true,
budget: 48000,
});
expect(formGroup().controls['startDate'].value).toEqual(new Date(2026, 2, 2));
});
it('shows a not-found state for an unknown id', async () => {
const el = await open('/projects/P-9999');
expect(el.textContent).toContain('Project not found');
expect(el.querySelector('form')).toBeNull();
});
it('shows a load error without technical details, and retries', async () => {
api.failing.set(true);
const el = await open('/projects/P-1001');
expect(el.textContent).toContain('The project could not be loaded');
expect(el.textContent).toContain('Check your connection and try again.');
expect(el.textContent).not.toContain('The server is not responding.');
api.failing.set(false);
Array.from(el.querySelectorAll('button'))
.find((button) => button.textContent?.includes('Try again'))
?.click();
await settle();
expect(input(el, 'Project name').value).toBe('Website relaunch');
});
it('reports invalid fields on submit and focuses the first one', async () => {
const el = await open('/projects/new');
expect(el.querySelector('h1')?.textContent).toContain('New project');
await submit(el);
const name = input(el, 'Project name');
expect(name.getAttribute('aria-invalid')).toBe('true');
expect(document.activeElement).toBe(name);
expect(toast.success).not.toHaveBeenCalled();
});
it('creates a project and continues on its URL', async () => {
const el = await open('/projects/new');
type(input(el, 'Project name'), 'Mobile app');
formGroup().patchValue({ clientId: 'contoso', startDate: new Date(2026, 6, 1) });
await submit(el);
expect(toast.success).toHaveBeenCalledWith('Mobile app was created.');
expect(TestBed.inject(Router).url).toBe('/projects/P-1003');
await settle();
expect(input(harness.routeNativeElement as HTMLElement, 'Project name').value).toBe(
'Mobile app',
);
});
it('stays where the user went when they left before a create finished', async () => {
const response = new Subject<Project>();
vi.spyOn(api, 'create').mockReturnValue(response);
const el = await open('/projects/new');
type(input(el, 'Project name'), 'Mobile app');
formGroup().patchValue({ clientId: 'contoso', startDate: new Date(2026, 6, 1) });
await submit(el);
confirm.ask.mockResolvedValueOnce(true);
await harness.navigateByUrl('/elsewhere');
expect(TestBed.inject(Router).url).toBe('/elsewhere');
response.next({
id: 'P-2000',
name: 'Mobile app',
clientId: 'contoso',
priority: 'medium',
startDate: '2026-07-01',
endDate: null,
budget: null,
billable: false,
description: '',
});
response.complete();
await settle();
expect(TestBed.inject(Router).url).toBe('/elsewhere');
});
it('saves an edit and keeps the form open without unsaved changes', async () => {
const el = await open('/projects/P-1002');
type(input(el, 'Project name'), 'Support portal v2');
await submit(el);
expect(toast.success).toHaveBeenCalledWith('Support portal v2 was saved.');
const page = harness.fixture.debugElement.query(By.directive(ProjectFormPage))
.componentInstance as ProjectFormPage;
expect(page.hasUnsavedChanges()).toBe(false);
});
it('keeps the input and reports a failed save', async () => {
const el = await open('/projects/P-1002');
type(input(el, 'Project name'), 'Renamed');
api.failing.set(true);
await submit(el);
expect(toast.error).toHaveBeenCalled();
expect(input(el, 'Project name').value).toBe('Renamed');
});
it('asks before leaving with unsaved changes', async () => {
const el = await open('/projects/P-1001');
type(input(el, 'Project name'), 'Changed');
await settle();
confirm.ask.mockResolvedValueOnce(false);
await harness.navigateByUrl('/elsewhere');
expect(confirm.ask).toHaveBeenCalledWith(
expect.objectContaining({ heading: 'Discard unsaved changes?' }),
);
expect(TestBed.inject(Router).url).toBe('/projects/P-1001');
confirm.ask.mockResolvedValueOnce(true);
await harness.navigateByUrl('/elsewhere');
expect(TestBed.inject(Router).url).toBe('/elsewhere');
});
it('leaves without asking when nothing changed', async () => {
await open('/projects/P-1001');
await harness.navigateByUrl('/elsewhere');
expect(confirm.ask).not.toHaveBeenCalled();
expect(TestBed.inject(Router).url).toBe('/elsewhere');
});
});
import type { Route, Routes } from '@angular/router';
import { unsavedChangesGuard } from './unsaved-changes-guard';
/** The form page route without a path, for mounting it under any URL. */
export const projectFormRoute: Route = {
title: 'Project',
loadComponent: () => import('./project-form-page').then((m) => m.ProjectFormPage),
canDeactivate: [unsavedChangesGuard],
};
/**
* Routes of the projects feature: `/projects/new` and `/projects/:id`. The
* `:id` parameter reaches the page as its `id` input, which needs
* `withComponentInputBinding()` in `provideRouter`. Load them from the app:
*
* ```ts
* {
* path: 'projects',
* providers: [{ provide: ProjectsApi, useClass: HttpProjectsApi }],
* loadChildren: () => import('./features/projects/feature/projects.routes').then((m) => m.projectsRoutes),
* }
* ```
*/
export const projectsRoutes: Routes = [
{ path: 'new', ...projectFormRoute },
{ path: ':id', ...projectFormRoute },
];
import { inject } from '@angular/core';
import type { CanDeactivateFn } from '@angular/router';
import { Confirm } from '@vigdx/ui/confirm-dialog';
/** A routed component that can hold edits the user has not saved. */
export interface HasUnsavedChanges {
hasUnsavedChanges(): boolean;
}
export const UNSAVED_CHANGES_TEXT = {
heading: 'Discard unsaved changes?',
message: 'You have changes that are not saved yet. Leave the page and lose them?',
accept: 'Discard changes',
reject: 'Keep editing',
};
/**
* Asks before leaving a page with unsaved changes, through the kit's `Confirm`
* dialog (needs `<vig-confirm-dialog />` in the app shell). Reusable for any
* component implementing `HasUnsavedChanges`:
*
* ```ts
* { path: ':id', loadComponent: …, canDeactivate: [unsavedChangesGuard] }
* ```
*/
export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
!component.hasUnsavedChanges() ||
inject(Confirm).ask({
heading: UNSAVED_CHANGES_TEXT.heading,
message: UNSAVED_CHANGES_TEXT.message,
acceptLabel: UNSAVED_CHANGES_TEXT.accept,
rejectLabel: UNSAVED_CHANGES_TEXT.reject,
variant: 'error',
});
import { parseIsoDate, toIsoDate } from '@vigdx/ui/date-picker';
import type { Project, ProjectDraft, ProjectPriority } from '../data-access/project';
/**
* The project as the form edits it: dates as `Date` (what `vig-date-picker`
* works with), empty choices as `null`. Shared by the Reactive Forms and the
* Signal Forms variant.
*/
export interface ProjectFormValue {
name: string;
clientId: string | null;
priority: ProjectPriority | null;
startDate: Date | null;
endDate: Date | null;
budget: number | null;
billable: boolean;
description: string;
}
/** Form values of a project, or of a blank one. */
export function toFormValue(project: Project | null): ProjectFormValue {
return {
name: project?.name ?? '',
clientId: project?.clientId ?? null,
priority: project?.priority ?? 'medium',
startDate: parseIsoDate(project?.startDate),
endDate: parseIsoDate(project?.endDate),
budget: project?.budget ?? null,
billable: project?.billable ?? false,
description: project?.description ?? '',
};
}
/**
* The draft to save. Only called with a valid form, so the required values
* are present; dates travel as `YYYY-MM-DD` calendar days, never as instants.
*/
export function toDraft(value: ProjectFormValue): ProjectDraft {
return {
name: value.name.trim(),
clientId: value.clientId ?? '',
priority: value.priority ?? 'medium',
startDate: toIsoDate(value.startDate) ?? '',
endDate: toIsoDate(value.endDate),
budget: value.budget,
billable: value.billable,
description: value.description.trim(),
};
}
export interface ProjectFormLabels {
basics: string;
name: string;
client: string;
clientPlaceholder: string;
priority: string;
priorities: Record<ProjectPriority, string>;
schedule: string;
startDate: string;
endDate: string;
endDateHint: string;
endBeforeStart: string;
budget: string;
budgetHint: string;
settings: string;
billable: string;
billableHint: string;
description: string;
discard: string;
save: string;
}
export const PROJECT_FORM_LABELS: ProjectFormLabels = {
basics: 'Basics',
name: 'Project name',
client: 'Client',
clientPlaceholder: 'Choose a client',
priority: 'Priority',
priorities: { low: 'Low', medium: 'Medium', high: 'High' },
schedule: 'Schedule and budget',
startDate: 'Start date',
endDate: 'End date',
endDateHint: 'Leave empty for an open-ended project.',
endBeforeStart: 'The end date cannot be before the start date.',
budget: 'Budget',
budgetHint: 'Required for billable projects.',
settings: 'Billing and notes',
billable: 'Billable',
billableHint: 'Billable projects are invoiced against their budget.',
description: 'Description',
discard: 'Discard changes',
save: 'Save project',
};
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Injector,
afterNextRender,
computed,
effect,
inject,
input,
output,
untracked,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
type AbstractControl,
FormControl,
FormGroup,
FormGroupDirective,
ReactiveFormsModule,
type ValidationErrors,
Validators,
} from '@angular/forms';
import { Button } from '@vigdx/ui/button';
import { Card } from '@vigdx/ui/card';
import { VigValueAccessor, focusFirstInvalid } from '@vigdx/ui/core';
import { DatePicker } from '@vigdx/ui/date-picker';
import { InputField } from '@vigdx/ui/input-field';
import { NumberInput } from '@vigdx/ui/number-input';
import { RadioGroup } from '@vigdx/ui/radio-group';
import { Select, type SelectOption } from '@vigdx/ui/select';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';
import {
type Client,
DESCRIPTION_MAX_LENGTH,
NAME_MAX_LENGTH,
PROJECT_PRIORITIES,
type Project,
type ProjectDraft,
type ProjectPriority,
endsBeforeStart,
} from '../data-access/project';
import {
PROJECT_FORM_LABELS,
type ProjectFormValue,
toDraft,
toFormValue,
} from './project-form-model';
/**
* Cross-field rule on the end date: it reads the sibling start date, so the
* error sits on the field the user has to fix (and `focusFirstInvalid`
* finds it). The form re-runs it whenever the start date changes.
*/
function endAfterStart(control: AbstractControl<Date | null>): ValidationErrors | null {
const start = control.parent?.get('startDate')?.value ?? null;
return endsBeforeStart(start, control.value) ? { endBeforeStart: true } : null;
}
/**
* The project form in Reactive Forms, split into card sections. Presentational:
* shows `project` (or a blank form), emits a valid draft through `save`, and
* lets the page ask whether there are unsaved changes (`isDirty`) or reset it
* after saving (`reset`). The Signal Forms variant is `ProjectSignalForm`.
*/
@Component({
selector: 'app-project-form',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
ReactiveFormsModule,
Button,
Card,
DatePicker,
InputField,
NumberInput,
RadioGroup,
Select,
ToggleSwitch,
VigValueAccessor,
],
template: `
<form
#formRef
class="flex flex-col gap-6"
[formGroup]="form"
[attr.aria-labelledby]="labelledBy()"
(ngSubmit)="submit()"
>
<vig-card [heading]="labels().basics" [headingLevel]="2">
<div class="grid gap-4 @lg:grid-cols-2">
<vig-input
class="@lg:col-span-2"
formControlName="name"
autocomplete="off"
[label]="labels().name"
[maxLength]="nameMaxLength"
/>
<vig-select
formControlName="clientId"
[label]="labels().client"
[placeholder]="labels().clientPlaceholder"
[filter]="true"
[options]="clientOptions()"
/>
<vig-radio-group
formControlName="priority"
orientation="horizontal"
[label]="labels().priority"
[options]="priorityOptions()"
/>
</div>
</vig-card>
<vig-card [heading]="labels().schedule" [headingLevel]="2">
<div class="grid gap-4 @lg:grid-cols-2">
<vig-date-picker formControlName="startDate" [label]="labels().startDate" />
<vig-date-picker
formControlName="endDate"
[label]="labels().endDate"
[hint]="labels().endDateHint"
[clearable]="true"
[errorMessages]="{ endBeforeStart: labels().endBeforeStart }"
/>
<vig-number-input
formControlName="budget"
currency="EUR"
[label]="labels().budget"
[hint]="labels().budgetHint"
[min]="0"
/>
</div>
</vig-card>
<vig-card [heading]="labels().settings" [headingLevel]="2">
<div class="flex flex-col gap-4">
<vig-toggle-switch
formControlName="billable"
[label]="labels().billable"
[hint]="labels().billableHint"
/>
<vig-input
formControlName="description"
[label]="labels().description"
[multiline]="true"
[autoResize]="true"
[rows]="3"
[maxLength]="descriptionMaxLength"
/>
</div>
</vig-card>
<div class="flex flex-wrap justify-end gap-2">
<vig-button
variant="secondary"
[label]="labels().discard"
[disabled]="saving()"
(click)="reset(project())"
/>
<vig-button type="submit" [label]="labels().save" [loading]="saving()" />
</div>
</form>
`,
host: { class: 'block @container' },
})
export class ProjectForm {
private readonly injector = inject(Injector);
/** The project to edit; `null` for a new one. Changing it resets the form. */
readonly project = input<Project | null>(null);
readonly clients = input<readonly Client[]>([]);
readonly saving = input(false);
/** Id of the heading that names the form. */
readonly labelledBy = input<string | null>(null);
readonly labels = input(PROJECT_FORM_LABELS);
readonly save = output<ProjectDraft>();
protected readonly nameMaxLength = NAME_MAX_LENGTH;
protected readonly descriptionMaxLength = DESCRIPTION_MAX_LENGTH;
protected readonly form = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.maxLength(NAME_MAX_LENGTH)],
}),
clientId: new FormControl<string | null>(null, Validators.required),
priority: new FormControl<ProjectPriority | null>('medium', Validators.required),
startDate: new FormControl<Date | null>(null, Validators.required),
endDate: new FormControl<Date | null>(null, endAfterStart),
budget: new FormControl<number | null>(null, Validators.min(0)),
billable: new FormControl(false, { nonNullable: true }),
description: new FormControl('', {
nonNullable: true,
validators: [Validators.maxLength(DESCRIPTION_MAX_LENGTH)],
}),
});
protected readonly clientOptions = computed<SelectOption[]>(() =>
this.clients().map((client) => ({ value: client.id, label: client.name })),
);
protected readonly priorityOptions = computed<SelectOption<ProjectPriority>[]>(() =>
PROJECT_PRIORITIES.map((value) => ({ value, label: this.labels().priorities[value] })),
);
private readonly formDirective = viewChild(FormGroupDirective);
private readonly formRef = viewChild.required<ElementRef<HTMLFormElement>>('formRef');
constructor() {
const { startDate, endDate, billable, budget } = this.form.controls;
// Cross-field rules live on the dependent field; re-run them when the other side changes.
startDate.valueChanges
.pipe(takeUntilDestroyed())
.subscribe(() => endDate.updateValueAndValidity());
// Conditional `required`: billable projects need a budget. Toggling the validator itself
// (rather than a custom one) gives the field its required marker and `aria-required`.
billable.valueChanges.pipe(takeUntilDestroyed()).subscribe((isBillable) => {
if (isBillable) budget.addValidators(Validators.required);
else budget.removeValidators(Validators.required);
budget.updateValueAndValidity();
});
effect(() => {
const project = this.project();
untracked(() => this.reset(project));
});
}
/** Whether the user changed anything since the last load, save or reset. */
isDirty(): boolean {
return this.form.dirty;
}
/** Shows `project` (or a blank form) without changes or errors. */
reset(project: Project | null): void {
const value: ProjectFormValue = toFormValue(project);
const directive = this.formDirective();
// `resetForm` also clears the submitted flag, so no error shows on the fresh form;
// before the first render the directive is not bound yet and the group resets alone.
if (directive?.form) directive.resetForm(value);
else this.form.reset(value);
}
protected submit(): void {
if (this.saving()) return;
if (this.form.invalid) {
this.form.markAllAsTouched();
afterNextRender(() => focusFirstInvalid(this.formRef()), { injector: this.injector });
return;
}
this.save.emit(toDraft(this.form.getRawValue()));
}
}
import { provideZonelessChangeDetection } from '@angular/core';
import { type ComponentFixture, TestBed } from '@angular/core/testing';
import type { FormGroup } from '@angular/forms';
import { provideVigdxUi } from '@vigdx/ui/core';
import type { Project, ProjectDraft } from '../data-access/project';
import { ProjectForm } from './project-form';
import { ProjectSignalForm } from './project-signal-form';
const PROJECT: Project = {
id: 'P-1',
name: 'Website relaunch',
clientId: 'northwind',
priority: 'high',
startDate: '2026-03-02',
endDate: '2026-06-30',
budget: 48000,
billable: true,
description: '',
};
const CLIENTS = [
{ id: 'northwind', name: 'Northwind Traders' },
{ id: 'contoso', name: 'Contoso' },
];
/** Both variants share inputs, outputs and behavior; only the forms API differs. */
describe.each([
{
name: 'ProjectForm (Reactive Forms)',
component: ProjectForm,
set: (fixture: ComponentFixture<ProjectForm | ProjectSignalForm>, patch: object) =>
(fixture.componentInstance as unknown as { form: FormGroup }).form.patchValue(patch),
},
{
name: 'ProjectSignalForm (Signal Forms)',
component: ProjectSignalForm,
set: (fixture: ComponentFixture<ProjectForm | ProjectSignalForm>, patch: object) =>
(
fixture.componentInstance as unknown as {
model: { update(fn: (value: object) => object): void };
}
).model.update((value) => ({ ...value, ...patch })),
},
])('$name', ({ component, set }) => {
let fixture: ComponentFixture<ProjectForm | ProjectSignalForm>;
let el: HTMLElement;
let saved: ProjectDraft[];
beforeEach(async () => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection(), provideVigdxUi()],
});
fixture = TestBed.createComponent<ProjectForm | ProjectSignalForm>(component);
fixture.componentRef.setInput('clients', CLIENTS);
saved = [];
fixture.componentInstance.save.subscribe((draft) => saved.push(draft));
el = fixture.nativeElement;
await fixture.whenStable();
});
const field = (selector: string, label: string) =>
Array.from(el.querySelectorAll<HTMLElement>(selector)).find((host) =>
host.textContent?.includes(label),
) as HTMLElement;
async function submit(): Promise<void> {
el.querySelector('form')?.dispatchEvent(new Event('submit', { cancelable: true }));
await new Promise((resolve) => setTimeout(resolve));
await fixture.whenStable();
}
it('renders the sections as cards with level-2 headings', () => {
const headings = Array.from(el.querySelectorAll('h2')).map((h) => h.textContent?.trim());
expect(headings).toEqual(['Basics', 'Schedule and budget', 'Billing and notes']);
});
it('shows a project and resets to it without changes', async () => {
fixture.componentRef.setInput('project', PROJECT);
await fixture.whenStable();
expect(field('vig-input', 'Project name').querySelector('input')?.value).toBe(
'Website relaunch',
);
expect(fixture.componentInstance.isDirty()).toBe(false);
});
it('blocks an empty submit and focuses the first invalid field', async () => {
await submit();
expect(saved).toEqual([]);
const name = field('vig-input', 'Project name').querySelector('input');
expect(name?.getAttribute('aria-invalid')).toBe('true');
expect(document.activeElement).toBe(name);
});
it('rejects an end date before the start date', async () => {
set(fixture, {
name: 'Launch',
clientId: 'contoso',
startDate: new Date(2026, 5, 10),
endDate: new Date(2026, 5, 1),
});
await submit();
expect(saved).toEqual([]);
expect(field('vig-date-picker', 'End date').textContent).toContain(
'The end date cannot be before the start date.',
);
});
it('requires a budget only for billable projects', async () => {
set(fixture, {
name: 'Launch',
clientId: 'contoso',
startDate: new Date(2026, 5, 10),
billable: true,
});
await fixture.whenStable();
// Required only while billable: the native required state, as in a plain required field.
const budget = () => field('vig-number-input', 'Budget').querySelector('input');
expect(budget()?.required).toBe(true);
await submit();
expect(saved).toEqual([]);
expect(field('vig-number-input', 'Budget').textContent).toContain('This field is required.');
set(fixture, { billable: false });
await fixture.whenStable();
expect(budget()?.required).toBe(false);
await submit();
expect(saved).toHaveLength(1);
});
it('emits the draft with calendar dates', async () => {
set(fixture, {
name: ' Launch ',
clientId: 'contoso',
startDate: new Date(2026, 5, 10),
endDate: new Date(2026, 5, 30),
budget: 1200,
billable: true,
});
await submit();
expect(saved).toEqual([
{
name: 'Launch',
clientId: 'contoso',
priority: 'medium',
startDate: '2026-06-10',
endDate: '2026-06-30',
budget: 1200,
billable: true,
description: '',
},
]);
});
});
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Injector,
afterNextRender,
computed,
effect,
inject,
input,
output,
signal,
untracked,
viewChild,
} from '@angular/core';
import {
FormField,
FormRoot,
form,
maxLength,
min,
required,
validate,
} from '@angular/forms/signals';
import { Button } from '@vigdx/ui/button';
import { Card } from '@vigdx/ui/card';
import { focusFirstInvalid } from '@vigdx/ui/core';
import { DatePicker } from '@vigdx/ui/date-picker';
import { InputField } from '@vigdx/ui/input-field';
import { NumberInput } from '@vigdx/ui/number-input';
import { RadioGroup } from '@vigdx/ui/radio-group';
import { Select, type SelectOption } from '@vigdx/ui/select';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';
import {
type Client,
DESCRIPTION_MAX_LENGTH,
NAME_MAX_LENGTH,
PROJECT_PRIORITIES,
type Project,
type ProjectDraft,
type ProjectPriority,
endsBeforeStart,
} from '../data-access/project';
import {
PROJECT_FORM_LABELS,
type ProjectFormValue,
toDraft,
toFormValue,
} from './project-form-model';
/**
* The same project form in Signal Forms (`@angular/forms/signals`): the
* model is a signal, the schema holds every rule — cross-field ones included,
* through `valueOf` — and `[formField]` binds the kit fields without
* `VigValueAccessor`. Same inputs, outputs and methods as `ProjectForm`, so
* the page can use either.
*/
@Component({
selector: 'app-project-signal-form',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
FormField,
FormRoot,
Button,
Card,
DatePicker,
InputField,
NumberInput,
RadioGroup,
Select,
ToggleSwitch,
],
host: { class: 'block @container' },
template: `
<form #formRef class="flex flex-col gap-6" [formRoot]="f" [attr.aria-labelledby]="labelledBy()">
<vig-card [heading]="labels().basics" [headingLevel]="2">
<div class="grid gap-4 @lg:grid-cols-2">
<vig-input
class="@lg:col-span-2"
autocomplete="off"
[formField]="f.name"
[label]="labels().name"
/>
<vig-select
[formField]="f.clientId"
[label]="labels().client"
[placeholder]="labels().clientPlaceholder"
[filter]="true"
[options]="clientOptions()"
/>
<vig-radio-group
orientation="horizontal"
[formField]="f.priority"
[label]="labels().priority"
[options]="priorityOptions()"
/>
</div>
</vig-card>
<vig-card [heading]="labels().schedule" [headingLevel]="2">
<div class="grid gap-4 @lg:grid-cols-2">
<vig-date-picker [formField]="f.startDate" [label]="labels().startDate" />
<vig-date-picker
[formField]="f.endDate"
[label]="labels().endDate"
[hint]="labels().endDateHint"
[clearable]="true"
/>
<vig-number-input
currency="EUR"
[formField]="f.budget"
[label]="labels().budget"
[hint]="labels().budgetHint"
/>
</div>
</vig-card>
<vig-card [heading]="labels().settings" [headingLevel]="2">
<div class="flex flex-col gap-4">
<vig-toggle-switch
[formField]="f.billable"
[label]="labels().billable"
[hint]="labels().billableHint"
/>
<vig-input
[formField]="f.description"
[label]="labels().description"
[multiline]="true"
[autoResize]="true"
[rows]="3"
/>
</div>
</vig-card>
<div class="flex flex-wrap justify-end gap-2">
<vig-button
variant="secondary"
[label]="labels().discard"
[disabled]="saving()"
(click)="reset(project())"
/>
<vig-button type="submit" [label]="labels().save" [loading]="saving()" />
</div>
</form>
`,
})
export class ProjectSignalForm {
private readonly injector = inject(Injector);
readonly project = input<Project | null>(null);
readonly clients = input<readonly Client[]>([]);
readonly saving = input(false);
readonly labelledBy = input<string | null>(null);
readonly labels = input(PROJECT_FORM_LABELS);
readonly save = output<ProjectDraft>();
protected readonly model = signal<ProjectFormValue>(toFormValue(null));
protected readonly f = form(
this.model,
(p) => {
required(p.name);
maxLength(p.name, NAME_MAX_LENGTH);
required(p.clientId);
required(p.priority);
required(p.startDate);
// Cross-field: `valueOf` reads the sibling, so the rule re-runs when either changes.
validate(p.endDate, ({ value, valueOf }) =>
endsBeforeStart(valueOf(p.startDate), value())
? { kind: 'endBeforeStart', message: this.labels().endBeforeStart }
: null,
);
required(p.budget, { when: ({ valueOf }) => valueOf(p.billable) });
min(p.budget, 0);
maxLength(p.description, DESCRIPTION_MAX_LENGTH);
},
{
// `[formRoot]` runs this on submit; invalid forms go to `onInvalid`
// with every field marked touched, so their errors show.
submission: {
action: async () => {
if (!this.saving()) this.save.emit(toDraft(this.model()));
return undefined;
},
onInvalid: () =>
afterNextRender(() => focusFirstInvalid(this.formRef()), { injector: this.injector }),
},
},
);
protected readonly clientOptions = computed<SelectOption[]>(() =>
this.clients().map((client) => ({ value: client.id, label: client.name })),
);
protected readonly priorityOptions = computed<SelectOption<ProjectPriority>[]>(() =>
PROJECT_PRIORITIES.map((value) => ({ value, label: this.labels().priorities[value] })),
);
private readonly formRef = viewChild.required<ElementRef<HTMLFormElement>>('formRef');
constructor() {
effect(() => {
const project = this.project();
untracked(() => this.reset(project));
});
}
isDirty(): boolean {
return this.f().dirty();
}
/** Shows `project` (or a blank form) without changes or errors. */
reset(project: Project | null): void {
this.f().reset(toFormValue(project));
}
}