@daltonr/pathwrite-angular
v0.8.0
Published
Angular adapter for @daltonr/pathwrite-core — RxJS observables, signal-friendly, with optional <pw-shell> default UI.
Downloads
1,656
Maintainers
Readme
@daltonr/pathwrite-angular
Angular @Injectable facade over @daltonr/pathwrite-core. Exposes path state and events as RxJS observables that work seamlessly with Angular signals, the async pipe, and takeUntilDestroyed.
Installation
npm install @daltonr/pathwrite-core @daltonr/pathwrite-angularExported Types
For convenience, this package re-exports core types so you don't need to import from @daltonr/pathwrite-core:
import {
PathFacade, // Angular-specific
PathEngine, // Re-exported from core (value + type)
PathData, // Re-exported from core
PathDefinition, // Re-exported from core
PathEvent, // Re-exported from core
PathSnapshot, // Re-exported from core
PathStep, // Re-exported from core
PathStepContext, // Re-exported from core
SerializedPathState // Re-exported from core
} from "@daltonr/pathwrite-angular";Setup
Provide PathFacade at the component level so each component gets its own isolated path instance, and Angular handles cleanup automatically via ngOnDestroy.
@Component({
// ...
providers: [PathFacade]
})
export class MyComponent {
protected readonly facade = inject(PathFacade);
// Reactive snapshot — updates whenever the path state changes
public readonly snapshot = toSignal(this.facade.state$, { initialValue: null });
constructor() {
// Automatically unsubscribes when the component is destroyed
this.facade.events$.pipe(takeUntilDestroyed()).subscribe((event) => {
console.log(event);
});
}
}PathFacade API
Observables and signals
| Member | Type | Description |
|--------|------|-------------|
| state$ | Observable<PathSnapshot \| null> | Current snapshot. null when no path is active. Backed by a BehaviorSubject — late subscribers receive the current value immediately. |
| stateSignal | Signal<PathSnapshot \| null> | Signal version of state$. Same value, updated synchronously. Use directly in signal-based components without toSignal(). |
| events$ | Observable<PathEvent> | All engine events: stateChanged, completed, cancelled, resumed. |
Methods
| Method | Description |
|--------|-------------|
| adoptEngine(engine) | Adopt an externally-managed PathEngine (e.g. from restoreOrStart()). The facade immediately reflects the engine's current state and forwards all subsequent events. The caller is responsible for the engine's lifecycle. |
| start(definition, data?) | Start or re-start a path. |
| restart(definition, data?) | Tear down any active path (without firing hooks) and start the given path fresh. Safe to call at any time. Use for "Start over" / retry flows. |
| startSubPath(definition, data?, meta?) | Push a sub-path. Requires an active path. meta is returned unchanged to onSubPathComplete / onSubPathCancel. |
| next() | Advance one step. Completes the path on the last step. |
| previous() | Go back one step. No-op when already on the first step of a top-level path. |
| cancel() | Cancel the active path (or sub-path). |
| setData(key, value) | Update a single data value; emits stateChanged. When TData is specified, key and value are type-checked against your data shape. |
| goToStep(stepId) | Jump directly to a step by ID. Calls onLeave/onEnter; bypasses guards and shouldSkip. |
| goToStepChecked(stepId) | Jump to a step by ID, checking canMoveNext (forward) or canMovePrevious (backward) first. Blocked if the guard returns false. |
| snapshot() | Synchronous read of the current PathSnapshot \| null. |
PathFacade accepts an optional generic PathFacade<TData>. Because Angular's DI cannot carry generics at runtime, narrow it with a cast at the injection site:
protected readonly facade = inject(PathFacade) as PathFacade<MyData>;
facade.snapshot()?.data.name; // typed as string (or whatever MyData defines)injectPath() — Recommended API for Components
New in v0.6.0 — injectPath() provides an ergonomic, signal-based API for accessing the path engine inside Angular components. This is the recommended approach for step components and forms — it mirrors React's usePathContext() and Vue's usePath() for consistency across frameworks.
Quick start
import { Component } from "@angular/core";
import { PathFacade, injectPath } from "@daltonr/pathwrite-angular";
@Component({
selector: "app-contact-step",
standalone: true,
providers: [PathFacade], // ← Required: provide at this component or a parent
template: `
@if (path.snapshot(); as s) {
<h2>{{ s.activeStep?.title }}</h2>
<input
type="text"
[value]="name"
(input)="updateName($any($event.target).value)"
/>
<button (click)="path.next()">Next</button>
}
`
})
export class ContactStepComponent {
protected readonly path = injectPath<ContactData>();
protected name = "";
protected updateName(value: string): void {
this.name = value;
this.path.setData("name", value); // ← No facade or template ref needed
}
}API
injectPath() returns an object with:
| Member | Type | Description |
|--------|------|-------------|
| snapshot | Signal<PathSnapshot \| null> | Current path snapshot as a signal. null when no path is active. |
| start(path, data?) | Promise<void> | Start or restart a path. |
| restart(path, data?) | Promise<void> | Tear down and restart fresh. |
| startSubPath(path, data?, meta?) | Promise<void> | Push a sub-path onto the stack. |
| next() | Promise<void> | Advance one step. |
| previous() | Promise<void> | Go back one step. |
| cancel() | Promise<void> | Cancel the active path. |
| setData(key, value) | Promise<void> | Update a single data field. Type-safe when TData is specified. |
| goToStep(stepId) | Promise<void> | Jump to a step by ID (no guard checks). |
| goToStepChecked(stepId) | Promise<void> | Jump to a step by ID (guard-checked). |
Type safety
Pass your data type as a generic to get full type checking:
interface ContactData {
name: string;
email: string;
}
const path = injectPath<ContactData>();
path.setData("name", "Jane"); // ✅ OK
path.setData("foo", 123); // ❌ Type error: "foo" not in ContactData
path.snapshot()?.data.name; // ✅ Typed as stringTyping setData key parameters
setData is typed as setData<K extends string & keyof TData>(key: K, value: TData[K]).
The string & intersection is necessary because keyof T includes number and symbol
(all valid JavaScript property key types), but setData only accepts string keys.
When writing a reusable update method that receives a field name as a parameter, use
string & keyof TData — not just keyof TData — to match the constraint:
// ❌ Type error: keyof ContactData is string | number | symbol
protected update(field: keyof ContactData, value: string): void {
this.path.setData(field, value);
}
// ✅ Correct: string & keyof ensures the type matches setData's signature
protected update(field: string & keyof ContactData, value: string): void {
this.path.setData(field, value);
}Inline string literals are always fine — this pattern only matters when passing a key as a variable.
Reading step data without local state
Rather than mirroring engine data into local component state, use a typed getter that reads directly from the snapshot signal. Angular tracks the signal read during template evaluation, so any engine update (including back-navigation) triggers a re-render automatically:
export class PersonalInfoStepComponent {
protected readonly path = injectPath<OnboardingData>();
// No local state, no ngOnInit, no dual-update event handlers.
protected get data(): OnboardingData {
return (this.path.snapshot()?.data ?? {}) as OnboardingData;
}
}Template reads from data; writes go directly to the engine:
<input [value]="data.firstName ?? ''"
(input)="path.setData('firstName', $any($event.target).value.trim())" />Requirements
- Angular 16+ (signals required)
PathFacademust be provided in the injector tree (either at the component or a parent component)
Compared to manual facade injection
Before (manual facade injection + template reference):
@Component({
providers: [PathFacade],
template: `
<pw-shell #shell ...>
<ng-template pwStep="contact">
<input (input)="shell.facade.setData('name', $any($event.target).value)" />
</ng-template>
</pw-shell>
`
})
export class MyComponent {
protected readonly facade = inject(PathFacade);
}After (with injectPath()):
@Component({
providers: [PathFacade],
template: `
<input (input)="updateName($any($event.target).value)" />
<button (click)="path.next()">Next</button>
`
})
export class MyStepComponent {
protected readonly path = injectPath<MyData>();
protected updateName(value: string): void {
this.path.setData("name", value); // ← Clean, no template ref
}
}The injectPath() approach:
- No template references — access the engine directly from the component class
- Signal-native —
path.snapshot()returns the reactive signal directly - Type-safe — generic parameter flows through to all methods
- Framework-consistent — matches React's
usePathContext()and Vue'susePath() - Less Angular-specific knowledge — just
inject()and signals, patterns Angular developers already know
Angular Forms integration — syncFormGroup
syncFormGroup eliminates the boilerplate of manually wiring an Angular
FormGroup to the path engine. Call it once (typically in ngOnInit) and every
form value change is automatically propagated to the engine via setData, keeping
canMoveNext guards reactive without any manual plumbing.
import { PathFacade, syncFormGroup } from "@daltonr/pathwrite-angular";
@Component({
providers: [PathFacade],
template: `
<form [formGroup]="form">
<input formControlName="name" />
<input formControlName="email" />
</form>
<button [disabled]="!(snapshot()?.canMoveNext)" (click)="facade.next()">Next</button>
`
})
export class DetailsStepComponent implements OnInit {
protected readonly facade = inject(PathFacade);
protected readonly snapshot = toSignal(this.facade.state$, { initialValue: null });
protected readonly form = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
});
async ngOnInit() {
await this.facade.start(myPath, { name: '', email: '' });
// Immediately syncs current form values and keeps them in sync on every change.
// Cleanup is automatic when the component is destroyed.
syncFormGroup(this.facade, this.form, inject(DestroyRef));
}
}The corresponding path definition can now use a clean canMoveNext guard with no
manual sync code in the template:
const myPath: PathDefinition = {
id: 'registration',
steps: [
{
id: 'details',
canMoveNext: (ctx) =>
typeof ctx.data.name === 'string' && ctx.data.name.trim().length > 0 &&
typeof ctx.data.email === 'string' && ctx.data.email.includes('@'),
},
{ id: 'review' },
],
};syncFormGroup signature
function syncFormGroup(
facade: PathFacade,
formGroup: FormGroupLike,
destroyRef?: DestroyRef
): () => void| Parameter | Type | Description |
|-----------|------|-------------|
| facade | PathFacade | The facade to write values into. |
| formGroup | FormGroupLike | Any Angular FormGroup (or any object satisfying the duck interface). |
| destroyRef | DestroyRef (optional) | Pass inject(DestroyRef) to auto-unsubscribe on component destroy. |
| returns | () => void | Cleanup function — call manually if not using DestroyRef. |
Behaviour details
- Immediate sync — current
getRawValue()is written on the first call, so guards evaluate against the real form state from the first snapshot. - Disabled controls included — uses
getRawValue()(notformGroup.value) so disabled controls are always synced. - Safe before
start()— if no path is active when a change fires, the call is silently ignored (no error). FormGroupLikeduck interface —@angular/formsis not a required import; any object withgetRawValue()andvalueChangesworks.
Lifecycle
PathFacade implements OnDestroy. When Angular destroys the providing component, ngOnDestroy is called automatically, which:
- Unsubscribes from the internal
PathEngine - Completes
state$andevents$
Using with signals (Angular 16+)
PathFacade ships a pre-wired stateSignal so no manual toSignal() call is
needed:
@Component({ providers: [PathFacade] })
export class MyComponent {
protected readonly facade = inject(PathFacade);
// Use stateSignal directly — no toSignal() required
protected readonly snapshot = this.facade.stateSignal;
// Derive computed values
public readonly isActive = computed(() => this.snapshot() !== null);
public readonly currentStep = computed(() => this.snapshot()?.stepId ?? null);
public readonly canAdvance = computed(() => this.snapshot()?.canMoveNext ?? false);
}If you prefer the Observable-based approach, toSignal() still works as before:
public readonly snapshot = toSignal(this.facade.state$, { initialValue: null });Using with the async pipe
<ng-container *ngIf="facade.state$ | async as s">
<p>{{ s.pathId }} / {{ s.stepId }}</p>
</ng-container>Peer dependencies
| Package | Version |
|---------|---------|
| @angular/core | >=16.0.0 |
| rxjs | >=7.0.0 |
Default UI — <pw-shell>
The Angular adapter ships an optional shell component that renders a complete progress indicator, step content area, and navigation buttons out of the box. You only need to define the per-step content.
The shell lives in a separate entry point so that headless-only usage does not pull in the Angular compiler:
import {
PathShellComponent,
PathStepDirective,
PathShellHeaderDirective,
PathShellFooterDirective,
} from "@daltonr/pathwrite-angular/shell";Usage
@Component({
imports: [PathShellComponent, PathStepDirective],
template: `
<pw-shell [path]="myPath" [initialData]="{ name: '' }" (completed)="onDone($event)">
<ng-template pwStep="details"><app-details-form /></ng-template>
<ng-template pwStep="review"><app-review-panel /></ng-template>
</pw-shell>
`
})
export class MyComponent {
protected myPath = coursePath;
protected onDone(data: PathData) { console.log("Done!", data); }
}Each <ng-template pwStep="<stepId>"> is rendered when the active step matches stepId. The shell handles all navigation internally.
⚠️ Important:
pwStepValues Must Match Step IDsThe string value passed to the
pwStepdirective must exactly match the corresponding step'sid:const myPath: PathDefinition = { id: 'signup', steps: [ { id: 'details' }, // ← Step ID { id: 'review' } // ← Step ID ] };<pw-shell [path]="myPath"> <ng-template pwStep="details"> <!-- ✅ Matches "details" step --> <app-details-form /> </ng-template> <ng-template pwStep="review"> <!-- ✅ Matches "review" step --> <app-review-panel /> </ng-template> <ng-template pwStep="foo"> <!-- ❌ No step with id "foo" --> <app-foo-panel /> </ng-template> </pw-shell>If a
pwStepvalue doesn't match any step ID, that template will never be rendered (silent — no error message).💡 Tip: Use your IDE's "Go to Definition" on the step ID in your path definition, then copy-paste the exact string when creating the
pwStepdirective. This ensures perfect matching and avoids typos.
Context sharing
PathShellComponent provides a PathFacade instance in its own providers array
and passes its component-level Injector to every step template via
ngTemplateOutletInjector. Step components can therefore resolve the shell's
PathFacade directly via inject() — no extra provider setup required:
// Step component — inject(PathFacade) resolves the shell's instance automatically
@Component({
template: `
<input [value]="snapshot()?.data?.['name'] ?? ''"
(input)="facade.setData('name', $event.target.value)" />
`
})
export class DetailsFormComponent {
protected readonly facade = inject(PathFacade);
protected readonly snapshot = this.facade.stateSignal;
}The parent component hosting <pw-shell> does not need its own
PathFacade provider. To access the facade from the parent, use @ViewChild:
@Component({
imports: [PathShellComponent, PathStepDirective],
template: `
<pw-shell #shell [path]="myPath" (completed)="onDone($event)">
<ng-template pwStep="details"><app-details-form /></ng-template>
</pw-shell>
`
})
export class MyComponent {
@ViewChild('shell', { read: PathShellComponent }) shell!: PathShellComponent;
protected onDone(data: PathData) { console.log('done', data); }
}Inputs
| Input | Type | Default | Description |
|-------|------|---------|-------------|
| path | PathDefinition | required | The path definition to drive. |
| initialData | PathData | {} | Initial data passed to facade.start(). |
| autoStart | boolean | true | Start the path automatically on ngOnInit. |
| backLabel | string | "Previous" | Previous button label. |
| nextLabel | string | "Next" | Next button label. |
| completeLabel | string | "Complete" | Complete button label (last step). |
| cancelLabel | string | "Cancel" | Cancel button label. |
| hideCancel | boolean | false | Hide the Cancel button. |
| hideProgress | boolean | false | Hide the progress indicator. Also hidden automatically for single-step top-level paths. |
| footerLayout | "wizard" \| "form" \| "auto" | "auto" | Footer button layout. "auto" uses "form" for single-step top-level paths, "wizard" otherwise. "wizard": Back on left, Cancel+Submit on right. "form": Cancel on left, Submit on right, no Back button. |
Outputs
| Output | Payload | Description |
|--------|---------|-------------|
| (completed) | PathData | Emitted when the path finishes naturally. |
| (cancelled) | PathData | Emitted when the path is cancelled. |
| (pathEvent) | PathEvent | Emitted for every engine event. |
Customising the header and footer
Use pwShellHeader and pwShellFooter directives to replace the built-in progress bar or navigation buttons with your own templates. Both are declared on <ng-template> elements inside the shell.
pwShellHeader — receives the current PathSnapshot as the implicit template variable:
@Component({
imports: [PathShellComponent, PathStepDirective, PathShellHeaderDirective],
template: `
<pw-shell [path]="myPath">
<ng-template pwShellHeader let-s>
<p>Step {{ s.stepIndex + 1 }} of {{ s.stepCount }} — {{ s.stepTitle }}</p>
</ng-template>
<ng-template pwStep="details"><app-details-form /></ng-template>
<ng-template pwStep="review"><app-review-panel /></ng-template>
</pw-shell>
`
})
export class MyComponent { ... }pwShellFooter — receives the snapshot as the implicit variable and an actions variable with all navigation callbacks:
@Component({
imports: [PathShellComponent, PathStepDirective, PathShellFooterDirective],
template: `
<pw-shell [path]="myPath">
<ng-template pwShellFooter let-s let-actions="actions">
<button (click)="actions.previous()" [disabled]="s.isFirstStep || s.isNavigating">Back</button>
<button (click)="actions.next()" [disabled]="!s.canMoveNext || s.isNavigating">
{{ s.isLastStep ? 'Complete' : 'Next' }}
</button>
</ng-template>
<ng-template pwStep="details"><app-details-form /></ng-template>
</pw-shell>
`
})
export class MyComponent { ... }actions (PathShellActions) contains: next, previous, cancel, goToStep, goToStepChecked, setData, restart. All return Promise<void>.
restart() restarts the shell's own [path] input with its own [initialData] input — useful for a "Start over" button in a custom footer.
Both directives can be combined. Only the sections you override are replaced — a custom header still shows the default footer, and vice versa.
Resetting the path
There are two ways to reset <pw-shell> to step 1.
Option 1 — Toggle mount (simplest, always correct)
Toggle an @if flag to destroy and recreate the shell. Every child component resets from scratch:
@if (isActive) {
<pw-shell [path]="myPath" (completed)="isActive = false" (cancelled)="isActive = false">
<ng-template pwStep="details"><app-details-form /></ng-template>
</pw-shell>
} @else {
<button (click)="isActive = true">Try Again</button>
}Option 2 — Call restart() on the shell ref (in-place, no unmount)
Use the existing #shell template reference — restart() is a public method:
<pw-shell #shell [path]="myPath" (completed)="onDone($event)">
<ng-template pwStep="details"><app-details-form /></ng-template>
</pw-shell>
<button (click)="shell.restart()">Try Again</button>restart() resets the path engine to step 1 with the original [initialData] without unmounting the component. Use this when you need to keep the shell mounted — for example, to preserve scroll position in a parent container or to drive a CSS transition.
Sub-Paths
Sub-paths allow you to nest multi-step workflows. Common use cases include:
- Running a child workflow per collection item (e.g., approve each document)
- Conditional drill-down flows (e.g., "Add payment method" modal)
- Reusable wizard components
Basic Sub-Path Flow
When a sub-path is active:
- The shell switches to show the sub-path's steps
- The progress bar displays sub-path steps (not main path steps)
- Pressing Back on the first sub-path step cancels the sub-path and returns to the parent
- The
PathFacade(and thusstate$,stateSignal) reflects the sub-path snapshot, not the parent's
Complete Example: Approver Collection
import { PathData, PathDefinition, PathFacade } from "@daltonr/pathwrite-angular";
// Sub-path data shape
interface ApproverReviewData extends PathData {
decision: "approve" | "reject" | "";
comments: string;
}
// Main path data shape
interface ApprovalWorkflowData extends PathData {
documentTitle: string;
approvers: string[];
approvals: Array<{ approver: string; decision: string; comments: string }>;
}
// Define the sub-path (approver review wizard)
const approverReviewPath: PathDefinition<ApproverReviewData> = {
id: "approver-review",
steps: [
{ id: "review", title: "Review Document" },
{
id: "decision",
title: "Make Decision",
canMoveNext: ({ data }) =>
data.decision === "approve" || data.decision === "reject",
validationMessages: ({ data }) =>
!data.decision ? ["Please select Approve or Reject"] : []
},
{ id: "comments", title: "Add Comments" }
]
};
// Define the main path
const approvalWorkflowPath: PathDefinition<ApprovalWorkflowData> = {
id: "approval-workflow",
steps: [
{
id: "setup",
title: "Setup Approval",
canMoveNext: ({ data }) =>
(data.documentTitle ?? "").trim().length > 0 &&
data.approvers.length > 0
},
{
id: "run-approvals",
title: "Collect Approvals",
// Block "Next" until all approvers have completed their reviews
canMoveNext: ({ data }) =>
data.approvals.length === data.approvers.length,
validationMessages: ({ data }) => {
const remaining = data.approvers.length - data.approvals.length;
return remaining > 0
? [`${remaining} approver(s) pending review`]
: [];
},
// When an approver finishes their sub-path, record the result
onSubPathComplete(subPathId, subPathData, ctx, meta) {
const approverName = meta?.approverName as string;
const result = subPathData as ApproverReviewData;
return {
approvals: [
...ctx.data.approvals,
{
approver: approverName,
decision: result.decision,
comments: result.comments
}
]
};
},
// If an approver cancels (presses Back on first step), you can track it
onSubPathCancel(subPathId, subPathData, ctx, meta) {
console.log(`${meta?.approverName} cancelled their review`);
// Optionally return data changes, or just log
}
},
{ id: "summary", title: "Summary" }
]
};
// Component
@Component({
selector: 'app-approval-workflow',
standalone: true,
imports: [PathShellComponent, PathStepDirective],
providers: [PathFacade],
template: `
<pw-shell [path]="approvalWorkflowPath" [initialData]="initialData">
<!-- Main path steps -->
<ng-template pwStep="setup">
<input [(ngModel)]="facade.snapshot()!.data.documentTitle" placeholder="Document title" />
<!-- approver selection UI here -->
</ng-template>
<ng-template pwStep="run-approvals">
<h3>Approvers</h3>
<ul>
@for (approver of facade.snapshot()!.data.approvers; track $index) {
<li>
{{ approver }}
@if (!hasApproval(approver)) {
<button (click)="launchReviewForApprover(approver, $index)">
Start Review
</button>
} @else {
<span>✓ {{ getApproval(approver)?.decision }}</span>
}
</li>
}
</ul>
</ng-template>
<ng-template pwStep="summary">
<h3>All Approvals Collected</h3>
<ul>
@for (approval of facade.snapshot()!.data.approvals; track approval.approver) {
<li>{{ approval.approver }}: {{ approval.decision }}</li>
}
</ul>
</ng-template>
<!-- Sub-path steps (must be co-located in the same pw-shell) -->
<ng-template pwStep="review">
<p>Review the document: "{{ facade.snapshot()!.data.documentTitle }}"</p>
</ng-template>
<ng-template pwStep="decision">
<label><input type="radio" value="approve" [(ngModel)]="facade.snapshot()!.data.decision" /> Approve</label>
<label><input type="radio" value="reject" [(ngModel)]="facade.snapshot()!.data.decision" /> Reject</label>
</ng-template>
<ng-template pwStep="comments">
<textarea [(ngModel)]="facade.snapshot()!.data.comments" placeholder="Optional comments"></textarea>
</ng-template>
</pw-shell>
`
})
export class ApprovalWorkflowComponent {
protected readonly facade = inject(PathFacade) as PathFacade<ApprovalWorkflowData>;
protected readonly approvalWorkflowPath = approvalWorkflowPath;
protected readonly initialData = { documentTitle: '', approvers: [], approvals: [] };
protected launchReviewForApprover(approverName: string, index: number): void {
// Pass correlation data via `meta` — it's echoed back to onSubPathComplete
void this.facade.startSubPath(
approverReviewPath,
{ decision: "", comments: "" },
{ approverName, approverIndex: index }
);
}
protected hasApproval(approver: string): boolean {
return this.facade.snapshot()!.data.approvals.some(a => a.approver === approver);
}
protected getApproval(approver: string) {
return this.facade.snapshot()!.data.approvals.find(a => a.approver === approver);
}
}Key Notes
1. Sub-path steps must be co-located with main path steps
All pwStep templates (main path + sub-path steps) live in the same <pw-shell>. When a sub-path is active, the shell renders the sub-path's step templates. This means:
- Parent and sub-path step IDs must not collide (e.g., don't use
summaryin both) - The shell matches step IDs from the current path only (main or sub), but all templates are registered globally
2. The meta correlation fieldstartSubPath accepts an optional third argument (meta) that is returned unchanged to onSubPathComplete and onSubPathCancel. Use it to correlate which collection item triggered the sub-path:
facade.startSubPath(subPath, initialData, { itemIndex: 3, itemId: "abc" });
// In the parent step:
onSubPathComplete(subPathId, subPathData, ctx, meta) {
const itemIndex = meta?.itemIndex; // 3
}3. Root progress bar persists during sub-paths
When snapshot.nestingLevel > 0, you're in a sub-path. The shell automatically renders a compact, muted root progress bar above the sub-path's own progress bar so users always see their place in the main flow. The steps array in the snapshot contains the sub-path's steps. Use snapshot.rootProgress (type RootProgress) in a custom pwShellHeader template to render your own persistent top-level indicator.
4. Accessing parent path data from sub-path components
There is currently no way to inject a "parent facade" in sub-path step components. If a sub-path step needs parent data (e.g., the document title), pass it via initialData when calling startSubPath:
facade.startSubPath(approverReviewPath, {
decision: "",
comments: "",
documentTitle: facade.snapshot()!.data.documentTitle // copy from parent
});Guards and Lifecycle Hooks
Defensive Guards (Important!)
Guards and validationMessages are evaluated before onEnter runs on first entry.
If you access fields in a guard that onEnter is supposed to initialize, the guard will throw a TypeError on startup. Write guards defensively using nullish coalescing:
// ✗ Unsafe — crashes if data.name is undefined
canMoveNext: ({ data }) => data.name.trim().length > 0
// ✓ Safe — handles undefined gracefully
canMoveNext: ({ data }) => (data.name ?? "").trim().length > 0Alternatively, pass initialData to start() / <pw-shell> so all fields are present from the first snapshot:
<pw-shell [path]="myPath" [initialData]="{ name: '', age: 0 }" />If a guard throws, the engine catches it, logs a warning, and returns true (allow navigation) as a safe default.
Async Guards and Validation Messages
Guards and validationMessages must be synchronous for inclusion in snapshots. Async functions are detected and warned about:
- Async
canMoveNext/canMovePreviousdefault totrue(optimistic) - Async
validationMessagesdefault to[]
The async version is still enforced during actual navigation (when you call next() / previous()), but the snapshot won't reflect the pending state. If you need async validation, perform it in the guard and store the result in data so the guard can read it synchronously.
isFirstEntry Flag
The PathStepContext passed to all hooks includes an isFirstEntry: boolean flag. It's true the first time a step is visited, false on re-entry (e.g., after navigating back then forward again).
Use it to distinguish initialization from re-entry:
{
id: "details",
onEnter: ({ isFirstEntry, data }) => {
if (isFirstEntry) {
// Only pre-fill on first visit, not when returning via Back
return { name: "Default Name" };
}
}
}Important: onEnter fires every time you enter the step. If you want "initialize once" behavior, either:
- Use
isFirstEntryto conditionally return data - Provide
initialDatatostart()instead of usingonEnter
Persistence
Use with @daltonr/pathwrite-store-http for automatic state persistence. The engine is created externally via restoreOrStart(), then handed to the facade via adoptEngine().
Simple persistence example
import { Component, inject, OnInit } from '@angular/core';
import { PathFacade, PathShellComponent, PathStepDirective } from '@daltonr/pathwrite-angular';
import { HttpStore, restoreOrStart, httpPersistence } from '@daltonr/pathwrite-store-http';
import { signupPath } from './signup-path';
@Component({
selector: 'app-signup-wizard',
standalone: true,
imports: [PathShellComponent, PathStepDirective],
providers: [PathFacade],
template: `
@if (ready) {
<pw-shell [path]="path" [autoStart]="false" (completed)="onComplete($event)">
<ng-template pwStep="details"><app-details-form /></ng-template>
<ng-template pwStep="review"><app-review-panel /></ng-template>
</pw-shell>
} @else {
<p>Loading…</p>
}
`
})
export class SignupWizardComponent implements OnInit {
private readonly facade = inject(PathFacade);
path = signupPath;
ready = false;
async ngOnInit() {
const store = new HttpStore({ baseUrl: '/api/wizard' });
const key = 'user:signup';
const { engine, restored } = await restoreOrStart({
store,
key,
path: this.path,
initialData: { name: '', email: '' },
observers: [
httpPersistence({ store, key, strategy: 'onNext' })
]
});
// Hand the running engine to the facade — it immediately
// reflects the engine's current state and forwards all events.
this.facade.adoptEngine(engine);
this.ready = true;
if (restored) {
console.log('Progress restored — resuming from', engine.snapshot()?.stepId);
}
}
onComplete(data: any) {
console.log('Wizard completed:', data);
}
}Key points
adoptEngine()connects the facade to an externally-created engine. No@ViewChildor shell reference needed — injectPathFacadedirectly.[autoStart]="false"prevents the shell from callingstart()on its own — the engine is already running.- The facade is the same one the shell uses (provided in the component's
providers), so the shell's template bindings, progress indicator, and navigation buttons all work automatically. restoreOrStart()handles the load-or-create logic: if saved state exists on the server, it restores the engine mid-flow; otherwise it starts fresh.
Styling
Import the optional stylesheet for sensible default styles. All visual values are CSS custom properties (--pw-*) so you can theme without overriding selectors.
In angular.json (recommended)
"styles": [
"src/styles.css",
"node_modules/@daltonr/pathwrite-angular/dist/index.css"
]In a global stylesheet
@import "@daltonr/pathwrite-angular/styles.css";Theming
Override any --pw-* variable to customise the appearance:
:root {
--pw-color-primary: #8b5cf6;
--pw-shell-radius: 12px;
}Available CSS Custom Properties
Layout:
--pw-shell-max-width— Maximum width of the shell (default:720px)--pw-shell-padding— Internal padding (default:24px)--pw-shell-gap— Gap between header, body, footer (default:20px)--pw-shell-radius— Border radius for cards (default:10px)
Colors:
--pw-color-bg— Background color (default:#ffffff)--pw-color-border— Border color (default:#dbe4f0)--pw-color-text— Primary text color (default:#1f2937)--pw-color-muted— Muted text color (default:#5b677a)--pw-color-primary— Primary/accent color (default:#2563eb)--pw-color-primary-light— Light primary for backgrounds (default:rgba(37, 99, 235, 0.12))--pw-color-btn-bg— Button background (default:#f8fbff)--pw-color-btn-border— Button border (default:#c2d0e5)
Validation:
--pw-color-error— Error text color (default:#dc2626)--pw-color-error-bg— Error background (default:#fef2f2)--pw-color-error-border— Error border (default:#fecaca)
Progress Indicator:
--pw-dot-size— Step dot size (default:32px)--pw-dot-font-size— Font size inside dots (default:13px)--pw-track-height— Progress track height (default:4px)
Buttons:
--pw-btn-padding— Button padding (default:8px 16px)--pw-btn-radius— Button border radius (default:6px)
© 2026 Devjoy Ltd. MIT License.
