# Toggle switch

An on/off switch for settings that take effect immediately, such as notifications or feature flags. For a choice that is confirmed with a submit button, use a checkbox.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-toggle-switch`
- Source: [libs/ui/src/lib/molecules/toggle-switch/toggle-switch.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/molecules/toggle-switch/toggle-switch.ts)

```typescript title="Import"
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';
```

## Basic

Bind `[(value)]` to a boolean signal. The label follows the switch and `hint` adds help text. Under right-to-left the track and thumb mirror; try the RTL switch below.

```typescript title="toggle-switch-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';

@Component({
  selector: 'app-toggle-switch-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ToggleSwitch],
  template: `
    <div class="flex flex-col gap-4">
      <vig-toggle-switch label="Email notifications" [(value)]="email" />
      <vig-toggle-switch
        label="Maintenance mode"
        hint="Visitors see a static page while this is on."
        [(value)]="maintenance"
      />
    </div>
    <p class="text-sm text-muted-foreground" role="status">
      Notifications are {{ email() ? 'on' : 'off' }}; maintenance mode is
      {{ maintenance() ? 'on' : 'off' }}.
    </p>
  `,
})
export class ToggleSwitchBasicDemo {
  protected readonly email = signal(true);
  protected readonly maintenance = signal(false);
}
```

## States

`disabled` greys the switch out. `readonly` keeps it focusable but ignores clicks and Space; explain why in the `hint`.

```typescript title="toggle-switch-states.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';

@Component({
  selector: 'app-toggle-switch-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ToggleSwitch],
  template: `
    <div class="grid gap-4 sm:grid-cols-2">
      <vig-toggle-switch label="Off" />
      <vig-toggle-switch label="On" [value]="true" />
      <vig-toggle-switch label="Disabled" [disabled]="true" />
      <vig-toggle-switch
        label="Managed by policy"
        hint="Your administrator controls this setting."
        [value]="true"
        [readonly]="true"
      />
    </div>
  `,
})
export class ToggleSwitchStatesDemo {}
```

## Hidden label

Where a column header already names the control, `hideLabel` hides the label text but keeps it as the accessible name. Include the row name so every label is unique.

```typescript title="toggle-switch-hidden-label.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';

@Component({
  selector: 'app-toggle-switch-hidden-label',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ToggleSwitch],
  template: `
    <table class="w-full max-w-md text-sm">
      <caption class="sr-only">
        Integrations
      </caption>
      <thead>
        <tr class="border-b border-border text-muted-foreground">
          <th scope="col" class="py-2 text-start font-medium">Integration</th>
          <th scope="col" class="py-2 text-end font-medium">Active</th>
        </tr>
      </thead>
      <tbody>
        @for (integration of integrations; track integration.name) {
          <tr class="border-b border-border-subtle">
            <th scope="row" class="py-2 text-start font-normal">{{ integration.name }}</th>
            <td class="py-2 text-end">
              <vig-toggle-switch
                class="inline-block"
                [label]="integration.name + ' active'"
                [hideLabel]="true"
                [value]="integration.active"
              />
            </td>
          </tr>
        }
      </tbody>
    </table>
  `,
})
export class ToggleSwitchHiddenLabelDemo {
  protected readonly integrations = [
    { name: 'Slack', active: true },
    { name: 'GitHub', active: false },
    { name: 'Calendar', active: true },
  ];
}
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`. Disabling the control disables the switch.

```typescript title="toggle-switch-reactive-forms.ts"
import { JsonPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { Button } from '@vigdx/ui/button';
import { VigValueAccessor } from '@vigdx/ui/core';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';

@Component({
  selector: 'app-toggle-switch-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, Button, ToggleSwitch, VigValueAccessor],
  template: `
    <form class="flex flex-col gap-4" [formGroup]="form">
      <div class="flex flex-col gap-3">
        <vig-toggle-switch label="Public profile" formControlName="publicProfile" />
        <vig-toggle-switch label="Show online status" formControlName="onlineStatus" />
      </div>
      <div class="flex gap-2">
        <vig-button label="Lock settings" variant="secondary" (click)="lock()" />
        <vig-button label="Unlock" variant="ghost" (click)="form.enable()" />
      </div>
      <pre class="rounded-input bg-subtle p-3 font-mono text-xs">{{
        form.getRawValue() | json
      }}</pre>
    </form>
  `,
})
export class ToggleSwitchReactiveFormsDemo {
  protected readonly form = new FormGroup({
    publicProfile: new FormControl(true, { nonNullable: true }),
    onlineStatus: new FormControl(false, { nonNullable: true }),
  });

  protected lock(): void {
    // Disabling the control disables the switch.
    this.form.disable();
  }
}
```

## Signal Forms

`vig-toggle-switch` implements `FormValueControl<boolean>`. A `disabled()` rule that returns a string disables the switch and shows the string as the reason.

```typescript title="toggle-switch-signal-forms.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormField, disabled, form } from '@angular/forms/signals';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';

@Component({
  selector: 'app-toggle-switch-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, ToggleSwitch],
  template: `
    <div class="flex flex-col gap-3">
      <vig-toggle-switch label="Automatic backups" [formField]="settings.backups" />
      <vig-toggle-switch label="Encrypt backups" [formField]="settings.encrypt" />
    </div>
    <p class="text-sm text-muted-foreground">
      Backups: {{ model().backups ? 'on' : 'off' }} · Encryption:
      {{ model().encrypt ? 'on' : 'off' }}
    </p>
  `,
})
export class ToggleSwitchSignalFormsDemo {
  protected readonly model = signal({ backups: true, encrypt: false });
  protected readonly settings = form(this.model, (path) => {
    // The reason is shown under the switch while it is disabled.
    disabled(path.encrypt, ({ valueOf }) =>
      valueOf(path.backups) ? false : 'Turn on automatic backups first.',
    );
  });
}
```

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="toggle-switch"][data-part="root"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="toggle-switch"]`

| Part | Element | data-state |
| --- | --- | --- |
| `root` | The `<label>` wrapping switch and text. | `checked, unchecked` |
| `input` | The visually hidden `role="switch"` checkbox. |   |
| `track` | The switch track. |   |
| `thumb` | The sliding thumb. |   |
| `label` | The label text. |   |
| `hint` | The `vig-hint` (a `display: contents` host; style its `text` part). |   |
| `disabled-reason` | The `vig-hint` with the disabled reason (`display: contents`). |   |
| `error` | The `vig-field-error` (a `display: contents` host; style its `message` part). |   |

## Accessibility

- A native checkbox with `role="switch"`, so screen readers announce it as a switch that is on or off; Space toggles it.
- The input sits inside its `<label>`, so the label text is the accessible name and clicking it toggles the switch. `label` is required, also with `hideLabel`.
- Hint, disabled reason and error are linked through `aria-describedby`; a touched, invalid switch sets `aria-invalid="true"`. `readonly` reverts each change and sets `aria-readonly="true"`.
- The track shows a focus ring on keyboard focus, and the thumb animation is turned off under `prefers-reduced-motion`.
- Changes apply at once, so do not hide them behind a save button; announce the result if it is not visible next to the switch.

## API

### ToggleSwitch

Selector: `vig-toggle-switch` · Kind: component

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Keeps the label for assistive tech only, e.g. inside a table cell or a matrix. |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `name` | `string` | `''` | — |
| `pending` | `boolean` | `false` | — |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `boolean` | `false` | — |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `touch` | `void` | — |
| `valueChange` | `boolean` | — |

#### Methods

| Signature | Description |
| --- | --- |
| `focus(options?: FocusOptions): void` | Moves focus to the control's interactive element (the input, or the trigger of a popup control). Signal Forms calls it through `field().focusBoundControl()`; the host element itself cannot take focus. |
| `reset(): void` | Returns the control to its pristine look: drops in-progress text, closes an open popup, clears errors the component raised itself and the submitted state of `errorDisplay: 'interacted'`. Signal Forms calls it from `field().reset()`; `VigValueAccessor` from `control.reset()`. It never changes the value: the bound form owns that. |

### VigValueAccessor

Kind: directive

Bridges the vigdx form fields to Reactive Forms (`formControl`, `formControlName`) and template-driven forms (`ngModel`). Import it next to the component; Signal Forms (`[formField]`) need no accessor.

#### Methods

| Signature | Description |
| --- | --- |
| `registerOnChange(fn: (value: unknown) => void): void` | — |
| `registerOnTouched(fn: () => void): void` | — |
| `setDisabledState(disabled: boolean): void` | — |
| `writeValue(value: unknown): void` | — |
