# Primitives

> Standalone directives that handle roles, keyboard, focus and announcements.

Framework: Angular (`@stepperize/angular`), Stepperize v9.
Source: https://stepperize.com/docs/v9/angular/guides/primitives

The primitives are attribute directives for your own elements. They render
nothing and style nothing; they take care of the parts that are easy to get
wrong: roles, ids, keyboard navigation, focus and announcements.

For a simple flow, your own buttons and an `@switch` are enough.

## Basic structure

```ts
import { ChangeDetectionStrategy, Component } from "@angular/core";
import { STEPPER_PRIMITIVES } from "@stepperize/angular";
import { checkout } from "./checkout";

@Component({
  selector: "app-checkout-steps",
  imports: [STEPPER_PRIMITIVES],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div [stepperRoot]="stepper">
      <ol stepperList>
        @for (step of stepper.steps; track step.id) {
          <li [stepperItem]="step">
            <button stepperTrigger>
              <span stepperIndicator></span>
              {{ step.title }}
            </button>
          </li>
        }
      </ol>

      <div stepperContent="shipping"><app-shipping-form /></div>
      <div stepperContent="payment"><app-payment-form /></div>
      <div stepperContent="review"><app-review /></div>

      <button stepperPrev>Back</button>
      <button stepperNext>Continue</button>
    </div>
  `,
})
export class CheckoutSteps {
  readonly stepper = checkout.injectStepper({ linear: true, onFinish: placeOrder });
}
```

The live demo runs in the browser. Its source ([mount/angular.ts](https://github.com/damianricobelli/stepperize/blob/main/apps/docs/src/components/framework-demos/mount/angular.ts)):

```ts
// The docs are not an Angular application, so there is no Angular compiler in the build: the
// demo loads the JIT compiler and declares its component with the function form of `Component`.
// In an application this is an ordinary `@Component` class, and with a `StepperRegistry`
// (see the primitives guide) the template type-checker checks every step id it names.
import "@angular/compiler";
import { ChangeDetectionStrategy, Component } from "@angular/core";
import { bootstrapApplication } from "@angular/platform-browser";
import { defineStepper, STEPPER_PRIMITIVES } from "@stepperize/angular";

const demo = defineStepper([
	{ id: "account", title: "Account", description: "Who you are" },
	{ id: "plan", title: "Plan", description: "What you need" },
	{ id: "done", title: "Done", description: "All set" },
]);

const TAG = "stepperize-angular-demo";
const panel = "rounded-md bg-fd-muted p-3";

const AngularDemo = Component({
	selector: TAG,
	imports: [STEPPER_PRIMITIVES],
	changeDetection: ChangeDetectionStrategy.OnPush,
	template: `
		<div
			[stepperRoot]="stepper"
			data-demo="angular"
			class="not-prose my-4 flex flex-col gap-4 rounded-lg border p-4 text-sm"
		>
			<ol stepperList class="flex gap-2">
				@for (step of stepper.steps; track step.id) {
					<li [stepperItem]="step" #item="stepperItem" class="flex-1">
						<button
							stepperTrigger
							class="flex w-full items-center gap-2 rounded-md border px-3 py-2 text-left data-[state=current]:border-fd-primary data-[state=current]:bg-fd-accent"
						>
							<span
								stepperIndicator
								class="flex size-6 shrink-0 items-center justify-center rounded-full border text-xs data-[state=complete]:bg-fd-primary data-[state=complete]:text-fd-primary-foreground"
								>{{ item.value().state === "complete" ? "✓" : item.value().index + 1 }}</span
							>
							<span class="flex flex-col">
								<span class="font-medium">{{ step.title }}</span>
								<span class="text-xs text-fd-muted-foreground">{{ item.value().step.description }}</span>
							</span>
						</button>
					</li>
				}
			</ol>
			<div stepperContent="account" class="${panel}">Create your account.</div>
			<div stepperContent="plan" class="${panel}">Pick the plan that fits.</div>
			<div stepperContent="done" class="${panel}" #done="stepperContent">
				@if (done.active()) {
					{{ stepper().isFinished ? "Finished. Thanks!" : "Press Finish to complete the flow." }}
				}
			</div>
			<div class="flex items-center gap-2">
				<button stepperPrev class="rounded-md border px-3 py-1 disabled:opacity-40">Back</button>
				<button stepperNext class="rounded-md border px-3 py-1 aria-disabled:opacity-40">
					{{ stepper().isLast ? "Finish" : "Continue" }}
				</button>
				<span data-step class="ml-auto text-xs text-fd-muted-foreground">
					Step {{ stepper().index + 1 }} of {{ stepper().steps.length }}
				</span>
			</div>
		</div>
	`,
})(
	class {
		readonly stepper = demo.injectStepper();
	},
);

export function mount(el: HTMLElement) {
	// `bootstrapApplication` renders into the first element that matches the selector.
	const host = document.createElement(TAG);
	el.appendChild(host);
	const application = bootstrapApplication(AngularDemo);
	return () => {
		void application.then((ref) => ref.destroy());
		host.remove();
	};
}
```

## How the pieces connect

1. `[stepperRoot]` takes the stepper your component created and marks the
   element that contains everything else. Components inside it can read that
   stepper with `injectStepperContext()`.
2. `stepperList` marks the list of steps and gives it arrow-key navigation.
3. `[stepperItem]` is one step, bound to the step or to its id. What is inside
   it knows which one.
4. `stepperTrigger` goes to that step when pressed.
5. `stepperIndicator` is a decorative mark, hidden from assistive technology.
6. `stepperContent` is the panel of a step, hidden unless its step is current.
7. `stepperPrev` and `stepperNext` call `prev()` and `next()`.

Import them one by one, or all at once with `STEPPER_PRIMITIVES`.

## Typed step ids

The stepper is always typed: `stepper().current.id`, `stepper().goTo("…")` and
`@case ("…")` on a step id are checked against your steps, in TypeScript and by
the template type-checker.

The directives are shared by every flow, so on their own they cannot know your
ids. Register your definitions once and they do:

```ts title="checkout.ts"
export const checkout = defineStepper([
  { id: "shipping", title: "Shipping", icon: "truck" },
  { id: "payment", title: "Payment", icon: "card" },
  { id: "review", title: "Review", icon: "list" },
]);

declare module "@stepperize/angular" {
  interface StepperRegistry {
    checkout: typeof checkout;
  }
}
```

With `strictTemplates` (the default in new Angular projects), a typo now fails
the build:

```text
<div stepperContent="shiping"> → Type '"shiping"' is not assignable to type
'"shipping" | "payment" | "review"'. Did you mean '"shipping"'?
```

What is checked:

| Where | Checked against |
| --- | --- |
| `stepperContent`, `stepperItem` with an id, `stepperTrigger`, `stepperIndicator` | The ids of every registered definition. |
| `[stepperItem]="step"` | Any step. `item.value().step` is that step, with its own fields typed. |
| `stepperItem="payment"` with a registry | `item.value().step` is the registered `payment` step. |

Register every definition whose ids you write in templates. The ids are checked
against all of them together, so an id of another registered flow is accepted.
Without a registry the ids are plain strings, and a wrong one is reported when
the template runs, with [SZ102](https://stepperize.com/docs/v9/core/errors#sz102) and the id in the
message.

## Three patterns, chosen for you

| The flow | What is rendered |
| --- | --- |
| Not `linear`, with triggers | A `tablist`: triggers are tabs with roving focus and arrow keys, panels are `tabpanel`s. |
| `linear` | An ordered list of buttons with `aria-current="step"`. Steps that cannot be reached yet are disabled. |
| No triggers | Panels are `group`s named by the step's `title`. |

On every step change, if the focused element was hidden or removed, focus
moves to the new panel instead of being lost, and the new step is announced to
screen readers by its `title`. The announcement is skipped when focus is
already on the new step's trigger or panel, which reads it out anyway.

## Styling

Nothing is styled. Every element has a `data-component` and the state it shows:

| Attribute | On | Values |
| --- | --- | --- |
| `data-state` | item, trigger, indicator | `pending`, `current`, `complete` |
| `data-invalid` | item, trigger, indicator | Present after a failed validation. |
| `data-disabled` | item, trigger, prev, next | Present when it cannot be used. |
| `data-pending` | root, prev, next | Present while an async check or `onFinish` runs. |
| `data-finished` | root | Present once the flow has finished. |
| `data-orientation` | root, list | `horizontal`, `vertical` |

```css
[data-component="stepper-trigger"][data-state="current"] { font-weight: 600; }
[data-component="stepper-indicator"][data-state="complete"] { background: green; }
```

The elements are in your template, so your component's styles apply to them.

## Your attributes stay

A static attribute you write on the root, the list, an item, a panel or an
indicator wins over the one the directive would set: `role="list"` on the list,
`tabindex` or `aria-labelledby` on a panel. On triggers and the prev and next
buttons the flow decides everything but `type`: a `<button>` gets
`type="button"` unless you wrote one, and `<input type="button" stepperNext>`
keeps its own.

## Reading a step's state

`stepperItem` exports itself. `value()` is what the item knows about its step;
bind the step itself and `value().step` has its fields, typed:

```html
@for (step of stepper.steps; track step.id) {
  <li [stepperItem]="step" #item="stepperItem">
    <button stepperTrigger>
      <app-icon [name]="item.value().step.icon" />
      {{ item.value().state === "complete" ? "✓" : item.value().index + 1 }} {{ step.title }}
    </button>
  </li>
}
```

Each item follows only its own step. A change that does not touch a step, such
as a draft saved for another one, does not update it.

## Handling the move yourself

A part acts after every `(click)` on its element has run. Call
`$event.preventDefault()` in yours to take over, for example to pass form
values:

```html
<button stepperNext (click)="$event.preventDefault(); stepper().next(form.getRawValue())">
  Continue
</button>
```

`$event.stopPropagation()` does not stop the part: a button inside a clickable
card still moves the flow. The same goes for `(keydown)` on the list and the
arrow keys.

## Panels in or out of the DOM

`stepperContent` keeps its element in the page while its step is not current,
with `hidden` and an inline `display: none`, so the components inside keep
their state, tabs always have the panel they point to, and a `display` rule of
yours does not show it by mistake. Only a rule marked `!important` overrides
it, so leave `display` without `!important` on panels.

To leave the content out instead, export the panel and use control flow.
`@defer` also loads the panel's code when its step is first shown:

```html
<div stepperContent="review" #review="stepperContent">
  @if (review.active()) {
    <app-review />
  }
</div>

<div stepperContent="payment" #payment="stepperContent">
  @defer (when payment.active()) {
    <app-payment-form />
  }
</div>
```

See the [primitives reference](https://stepperize.com/docs/v9/angular/api/primitives) for every
input.
