# Switch

Turn a setting on or off.

Use a switch for a setting that takes effect as soon as it changes, like Airplane mode or a notification preference. Keep its label the same in both states: the label says what the setting is, and the switch shows whether it's on.

```angular-ts title="basic.ts"
import { Component } from "@angular/core"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [Switch, SwitchThumb],
  template: `
    <label data-slot="label">
      Airplane mode
      <button uiSwitch>
        <span uiSwitchThumb></span>
      </button>
    </label>
  `,
})
class Example {}

export { Example }
```

Click Airplane mode, or focus the switch and press Space, to turn it on and off.

## Installation

```bash
npm install @ui-sdk/angular @ui-sdk/core
```

## Composition

Use the following composition to build Switch:

```text
uiSwitch
└── uiSwitchThumb
```

Wrap the switch and its text in a label. The thumb stays mounted and gets the switch's state, so CSS can slide it from one end to the other.

## Usage

Import the parts and put them together:

```ts
import { Component } from "@angular/core"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  selector: "app-example",
  imports: [Switch, SwitchThumb],
  template: `
    <label>
      Airplane mode
      <button uiSwitch>
        <span uiSwitchThumb></span>
      </button>
    </label>
  `,
})
class Example {}

export { Example }
```

## Description

Use `uiFieldLabel` and `uiFieldDescription` when a setting needs more explanation. The field connects both to the switch.

```angular-ts title="description.ts"
import { Component } from "@angular/core"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/angular/field"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [Field, FieldDescription, FieldLabel, Switch, SwitchThumb],
  template: `
    <div uiField>
      <div data-slot="stack">
        <label uiFieldLabel>Weekly digest</label>
        <p uiFieldDescription>A summary of your week, every Monday.</p>
      </div>
      <button uiSwitch>
        <span uiSwitchThumb></span>
      </button>
    </div>
  `,
})
class Example {}

export { Example }
```

Click Weekly digest. The field connects the label and description to the switch.

## Choice Card

A setting can fill a whole card. Here the label's `::after` covers the card, so a click anywhere on it toggles the switch, and `:has([data-checked])` marks the cards that are on.

```angular-ts title="choice-card.ts"
import { Component } from "@angular/core"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/angular/field"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [Field, FieldDescription, FieldLabel, Switch, SwitchThumb],
  template: `
    <div data-slot="stack">
      @for (setting of settings; track setting.label) {
        <div uiField data-variant="card">
          <div data-slot="stack">
            <label uiFieldLabel>{{ setting.label }}</label>
            <p uiFieldDescription>{{ setting.description }}</p>
          </div>
          <button uiSwitch [defaultChecked]="setting.defaultChecked">
            <span uiSwitchThumb></span>
          </button>
        </div>
      }
    </div>
  `,
})
class Example {
  readonly settings = [
    {
      label: "Public profile",
      description: "Anyone can see your name and photo.",
      defaultChecked: false,
    },
    {
      label: "Show activity status",
      description: "Teammates can see when you're online.",
      defaultChecked: true,
    },
  ]
}

export { Example }
```

Click anywhere on the Public profile card to turn it on. Each card's switch keeps its own value.

## Disabled

`disabled` prevents focus and changes, and leaves the switch out of form submissions. A disabled `fieldset` does the same.

```angular-ts title="disabled.ts"
import { Component } from "@angular/core"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [Switch, SwitchThumb],
  template: `
    <div data-slot="stack">
      <label data-slot="label">
        Product updates
        <button uiSwitch>
          <span uiSwitchThumb></span>
        </button>
      </label>
      <label data-slot="label">
        Security alerts
        <button uiSwitch defaultChecked disabled>
          <span uiSwitchThumb></span>
        </button>
      </label>
    </div>
  `,
})
class Example {}

export { Example }
```

Security alerts are always on, so that switch is disabled. Clicking it leaves it on, and Tab skips it.

## Read-Only

`readOnly` keeps the switch focusable and included in form submissions, while preventing the user from changing it. Use it for a setting managed somewhere else.

```angular-ts title="read-only.ts"
import { Component } from "@angular/core"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/angular/field"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [Field, FieldDescription, FieldLabel, Switch, SwitchThumb],
  template: `
    <div uiField>
      <div data-slot="stack">
        <label uiFieldLabel>Encrypt backups</label>
        <p uiFieldDescription>Your organization manages this setting.</p>
      </div>
      <button uiSwitch name="encrypt" defaultChecked readOnly>
        <span uiSwitchThumb></span>
      </button>
    </div>
  `,
})
class Example {}

export { Example }
```

Tab to Encrypt backups. Space and clicks leave it on.

## Controlled

Bind `[(checked)]`, or pass `checked` and handle `(beforeCheckedChange)`, to own the value. A [controller](#controller) from `createSwitchController()` changes it from anywhere, like the Toggle button below. See [State and Events](/docs/angular/state-and-events) for the shared change callback.

```angular-ts title="controlled.ts"
import { Component, signal } from "@angular/core"
import { useLog } from "./log"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"
import { createSwitchController } from "@ui-sdk/core/switch"

@Component({
  imports: [Switch, SwitchThumb],
  template: `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" (click)="wifi.toggle()">Toggle</button>
      </div>
      <label data-slot="label">
        Wi-Fi
        <button
          uiSwitch
          [(checked)]="checked"
          (beforeCheckedChange)="
            log(($event.value ? 'On' : 'Off') + ' (' + $event.reason + ')')
          "
          [controller]="wifi"
        >
          <span uiSwitchThumb></span>
        </button>
      </label>
    </div>
  `,
})
class Example {
  readonly log = useLog()

  readonly wifi = createSwitchController()

  readonly checked = signal(true)
}

export { Example }
```

Turn Wi-Fi off, or press Toggle. The console logs each change and its reason.

## Form

Set `name` to include the switch in a native form. A switch that's on submits its `value`, which defaults to `"on"`; a switch that's off submits nothing. Reset returns it to `defaultChecked`. Set `form` to a form's id to join it from elsewhere on the page.

```angular-ts title="form.ts"
import { Component } from "@angular/core"
import { useLog } from "./log"
import { FieldLegend, FieldSet } from "@ui-sdk/angular/field"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [FieldLegend, FieldSet, Switch, SwitchThumb],
  template: `
    <form data-slot="stack" (submit)="onSubmit($event)">
      <fieldset uiFieldSet>
        <legend uiFieldLegend>Email notifications</legend>
        <label data-slot="label">
          Product updates
          <button uiSwitch name="updates">
            <span uiSwitchThumb></span>
          </button>
        </label>
        <label data-slot="label">
          Security alerts
          <button uiSwitch name="security" defaultChecked>
            <span uiSwitchThumb></span>
          </button>
        </label>
        <label data-slot="label">
          Weekly digest
          <button uiSwitch name="digest" value="weekly" defaultChecked>
            <span uiSwitchThumb></span>
          </button>
        </label>
      </fieldset>
      <div data-slot="row">
        <button type="submit" data-variant="solid">Save</button>
        <button type="reset">Reset</button>
      </div>
    </form>
  `,
})
class Example {
  readonly log = useLog()

  onSubmit(event: SubmitEvent) {
    event.preventDefault()
    const entries = [
      ...new FormData(event.currentTarget as HTMLFormElement),
    ].map(([name, value]) => `${name}=${value}`)
    this.log(
      entries.length ? `Submitted ${entries.join("&")}` : "Submitted nothing"
    )
  }
}

export { Example }
```

Turn on Product updates and press Save. The console logs the submitted values, and Reset restores the defaults.

## Validation

`required` blocks submission until the switch is on. In a [Field](/docs/angular/components/field), `uiFieldError` shows the message under the switch and connects it to the switch. [Forms and Validation](/docs/angular/forms) covers the shared field behavior.

```angular-ts title="invalid.ts"
import { Component } from "@angular/core"
import { useLog } from "./log"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/angular/field"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
    Switch,
    SwitchThumb,
  ],
  template: `
    <form data-slot="stack" (submit)="onSubmit($event)">
      <div uiField>
        <div data-slot="row">
          <div data-slot="stack">
            <label uiFieldLabel>Two-factor authentication</label>
            <p uiFieldDescription>Required for admins of this workspace.</p>
          </div>
          <button uiSwitch name="two-factor" required>
            <span uiSwitchThumb></span>
          </button>
        </div>
        <div *uiFieldError="'valueMissing'">Turn this on to continue.</div>
      </div>
      <div data-slot="row">
        <button type="submit" data-variant="solid">Continue</button>
      </div>
    </form>
  `,
})
class Example {
  readonly log = useLog()

  onSubmit(event: SubmitEvent) {
    event.preventDefault()
    this.log(
      `Submitted two-factor=${new FormData(event.currentTarget as HTMLFormElement).get("two-factor")}`
    )
  }
}

export { Example }
```

Press Continue with the switch off to see the error. Turn on Two-factor authentication and continue; the console logs the submitted value.

## Saving on Toggle

To save a change before it shows, call `$event.cancel()` in `(beforeCheckedChange)` to keep the current value while the save runs. When it finishes, call `controller.setChecked(next, { reason: "imperative" })`, and let that reason through in the callback so the saved value commits. An agent's change reports `"imperative"` too, with `source` set to `"agent"`, so the example checks `source` and saves it like any other change.

The example ignores presses while a save is running, and shows a spinner in the thumb. `aria-busy` tells assistive technology the switch is busy; the callback is what blocks another change.

```angular-ts title="async.ts"
import { Component, signal } from "@angular/core"
import { LucideLoaderCircle } from "@lucide/angular"
import { createSwitchController } from "@ui-sdk/core/switch"
import {
  Switch,
  SwitchThumb,
  type SwitchCheckedChange,
} from "@ui-sdk/angular/switch"
import { useLog } from "./log"

@Component({
  imports: [Switch, SwitchThumb, LucideLoaderCircle],
  template: `
    <label data-slot="label">
      Automatic backups
      <button
        uiSwitch
        [controller]="backups"
        [attr.aria-busy]="saving()"
        (beforeCheckedChange)="onCheckedChange($event)"
      >
        <span uiSwitchThumb>
          @if (saving()) {
            <svg lucideLoaderCircle data-slot="spinner"></svg>
          }
        </span>
      </button>
    </label>
  `,
})
class Example {
  readonly log = useLog()
  readonly backups = createSwitchController()
  readonly saving = signal(false)

  onCheckedChange(change: SwitchCheckedChange) {
    if (change.reason === "imperative" && change.source !== "agent") {
      return
    }
    change.cancel()
    if (this.saving()) {
      return
    }
    this.saving.set(true)
    this.log("Saving…")
    const next = change.value
    setTimeout(() => {
      this.backups.setChecked(next, { reason: "imperative" })
      this.saving.set(false)
      this.log(`Saved: ${next ? "on" : "off"}`)
    }, 800)
  }
}

export { Example }
```

Turn on Automatic backups. The thumb shows a spinner while it saves, then the switch turns on.

## Custom Rendering

The switch and thumb go on elements you write. Read their state from a template reference: with `#darkMode="uiSwitch"`, `darkMode.state().checked` says whether it's on. See [Parts and Composition](/docs/angular/parts-and-composition) for more.

```angular-ts title="render.ts"
import { Component } from "@angular/core"
import { LucideMoon, LucideSun } from "@lucide/angular"
import { Switch, SwitchThumb } from "@ui-sdk/angular/switch"

@Component({
  imports: [Switch, SwitchThumb, LucideMoon, LucideSun],
  template: `
    <label data-slot="label">
      Dark mode
      <button uiSwitch #darkMode="uiSwitch">
        <span uiSwitchThumb>
          @if (darkMode.state().checked) {
            <svg lucideMoon></svg>
          } @else {
            <svg lucideSun></svg>
          }
        </span>
      </button>
    </label>
  `,
})
class Example {}

export { Example }
```

Turn on Dark mode. The thumb renders a sun or a moon from its state.

## Styling

Style the switch and its thumb with `data-checked` and `data-unchecked`, and use `data-disabled`, `data-readonly` and `data-required` for the rest. In an invalid field, the switch also gets `data-invalid` and `aria-invalid`; the thumb doesn't. Slide the thumb with `translate` on `data-checked`, and reverse it under `dir="rtl"`.

Each part has a `data-slot`, such as `switch`, and its state attributes are listed under [Data Attributes](#data-attributes).

## Data Attributes

### Switch
`[data-slot="switch"]`

- `data-checked`: Present while on.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while off.
- `data-invalid`: Present while a `Field` around it shows as invalid. The thumb doesn't get it.

### SwitchThumb
`[data-slot="switch-thumb"]`

- `data-checked`: Present while on.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while off.

## API Reference

Each option below is an input on the directive, and each callback an output. A change callback is two outputs: `(beforeCheckedChange)`, with the details and `cancel()`, then `(checkedChange)` with the new value alone. Bind `checked` with `[(checked)]`.

### Switch

- `checked?` (`boolean`): Whether it's checked. Pass it to control the checkbox.
- `defaultChecked?` (`boolean`): Whether it's checked at first, when uncontrolled. A form reset returns to it.
- `(beforeCheckedChange)`: Runs when a user or a form reset wants to change it. `details.reason` says why, and `details.cancel()` stops it.
- `disabled?` (`boolean`): Disables it like a native control: it can't be focused or changed, and isn't submitted.
- `readOnly?` (`boolean`): Keeps it focusable and submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission until it's checked, with the browser's own message.
- `name?` (`string`): The name it submits under. Without one, it submits nothing.
- `value?` (`string`): What it submits while checked.
- `form?` (`string`): The id of a form to belong to, when it isn't inside that form.
- `controller?` (`{ toggle: (details?: Details) => boolean; getChecked: () => boolean; setChecked: (checked: boolean, details?: Details) => boolean; focus: () => void; }`): Toggles it from anywhere. Create one with `createSwitchController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### State

What each part's `state()` signal holds. The thumb's state, `SwitchThumbState`, is the same.

- `checked` (`boolean`): Whether it's checked. False while indeterminate.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but presses don't change it.
- `required` (`boolean`): Whether a form won't submit until it's checked. Indeterminate doesn't count.

### Reasons

`$event.reason` says why the switch turned on or off.

- `press` (`MouseEvent | KeyboardEvent`): A single-element control was pressed: a checkbox, a switch or a toggle.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### Controller

Create one with `createSwitchController()` and pass it as `controller`.

Every write method takes an optional `{ reason, event }`, runs the change callback like a press, and returns `false` when the change is canceled.

- `toggle(details?)` (`(details?: CheckboxChangeOptions | undefined) => boolean`): Turns it on, or off.
- `getChecked()` (`() => boolean`): Whether it's on.
- `setChecked(checked, details?)` (`(checked: boolean, details?: CheckboxChangeOptions | undefined) => boolean`): Turns it on or off, as a user would.
- `focus()` (`() => void`): Moves focus to it.

### Events

A `before` output emits `{ value, reason, event, cancel() }` before the change, and its plain output follows with the value alone. A bound `checked` only updates when `(beforeCheckedChange)` wasn't canceled.

| Binding                 | On         | Receives                                                                 |
| ----------------------- | ---------- | ------------------------------------------------------------------------ |
| `[(checked)]`           | `uiSwitch` | Whether the switch is on                                                 |
| `(beforeCheckedChange)` | `uiSwitch` | `{ value, reason, cancel() }`: the new state, and the [reason](#reasons) |

## Accessibility

The switch follows the [WAI-ARIA switch pattern](https://www.w3.org/WAI/ARIA/apg/patterns/switch/). `uiSwitch` renders a button with the `switch` role, and a hidden native checkbox that takes part in forms.

### Keyboard

| Key   | Does                                   |
| ----- | -------------------------------------- |
| Tab   | Moves to the next switch               |
| Space | Turns it on or off                     |
| Enter | Submits its form, and never toggles it |

### Tested Behavior

Every line below is an automated test.

- Starts in its default state.
- Clicking toggles it.
- Clicking its label toggles it.
- Space toggles it.
- Enter submits the form and never toggles it.
- The thumb follows the state.

**The first input on a page**

- The first Space reports keyboard.

**On a touch screen**

- The first tap reports touch.

Runs in React, Vue and web components.

In forms:

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React, Vue and web components.

Beyond the pattern's baseline:

**Enhancements**

- The first invalid control takes focus in document order.
- A later required field without an error part doesn't take focus from the first.

**Form-associated custom elements**

- Take part in the form with no hidden input. Web components only.
- Report validity like native controls. Web components only.
- Have live checked and value properties. Web components only.
- Are named by their labels. Web components only.

Runs in React, Vue and web components.

Screen readers hear the same thing in each tested framework, recorded by a virtual screen reader:

- Announcements while checking boxes with a keyboard.
- Announcements while choosing a radio with a keyboard.

Runs in React, Vue and web components.
