# Toggle button

A button that stays pressed or not pressed, for a yes/no choice that reads as an action: follow, pin, show a layer or turn on a filter. Its value is a boolean.

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

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

## Basic

Bind `[(value)]` to a boolean signal. `onLabel` is shown while pressed and `offLabel` while not pressed; the pressed style uses the primary colour.

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

@Component({
  selector: 'app-toggle-button-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ToggleButton],
  template: `
    <div class="flex flex-wrap items-center gap-3">
      <vig-toggle-button onLabel="Following" offLabel="Follow" [(value)]="following" />
      <vig-toggle-button onLabel="Subscribed" offLabel="Subscribe" [(value)]="subscribed" />
    </div>
    <p class="text-sm text-muted-foreground">
      Following: {{ following() }} · Subscribed: {{ subscribed() }}
    </p>
  `,
})
export class ToggleButtonBasicDemo {
  protected readonly following = signal(false);
  protected readonly subscribed = signal(true);
}
```

## Single label

Without `offLabel` the button keeps the `onLabel` text in both states and only its style and `aria-pressed` change. This suits filter chips and layer switches.

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

@Component({
  selector: 'app-toggle-button-single-label',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ToggleButton],
  template: `
    <div class="flex flex-wrap items-center gap-2" role="group" aria-label="Filters">
      <vig-toggle-button onLabel="Unread only" />
      <vig-toggle-button onLabel="With attachments" [value]="true" />
      <vig-toggle-button onLabel="Flagged" />
    </div>
  `,
})
export class ToggleButtonSingleLabelDemo {}
```

## Accessible name

When the visible text is too short to make sense on its own, `ariaLabel` sets the accessible name. It is also the hook for translating that name.

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

@Component({
  selector: 'app-toggle-button-aria-label',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ToggleButton],
  template: `
    <div class="flex items-center gap-1" role="group" aria-label="Text style">
      <vig-toggle-button onLabel="B" ariaLabel="Bold" />
      <vig-toggle-button onLabel="I" ariaLabel="Italic" [value]="true" />
      <vig-toggle-button onLabel="U" ariaLabel="Underline" />
    </div>
  `,
})
export class ToggleButtonAriaLabelDemo {}
```

## Disabled

`disabled` keeps the current state visible but removes the button from the tab order; use `hint` to say why it cannot be changed.

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

@Component({
  selector: 'app-toggle-button-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ToggleButton],
  template: `
    <div class="flex flex-wrap items-start gap-3">
      <vig-toggle-button onLabel="Pinned" offLabel="Pin" [disabled]="true" />
      <vig-toggle-button
        onLabel="Archived"
        offLabel="Archive"
        hint="Only owners can change this."
        [value]="true"
        [disabled]="true"
      />
    </div>
  `,
})
export class ToggleButtonStatesDemo {}
```

## Reactive Forms

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

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

@Component({
  selector: 'app-toggle-button-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, ToggleButton, VigValueAccessor],
  template: `
    <form class="flex flex-col gap-4" [formGroup]="form">
      <div class="flex flex-wrap gap-2" role="group" aria-label="Report options">
        <vig-toggle-button onLabel="Include drafts" formControlName="drafts" />
        <vig-toggle-button onLabel="Include archived" formControlName="archived" />
      </div>
      <pre class="rounded-input bg-subtle p-3 font-mono text-xs">{{ form.value | json }}</pre>
    </form>
  `,
})
export class ToggleButtonReactiveFormsDemo {
  protected readonly form = new FormGroup({
    drafts: new FormControl(true, { nonNullable: true }),
    archived: new FormControl(false, { nonNullable: true }),
  });
}
```

## Signal Forms

`vig-toggle-button` implements `FormValueControl<boolean>`, so `[formField]` binds each button to a boolean field of the model.

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

@Component({
  selector: 'app-toggle-button-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, ToggleButton],
  template: `
    <div class="flex flex-wrap gap-2" role="group" aria-label="Map layers">
      <vig-toggle-button onLabel="Traffic" [formField]="layers.traffic" />
      <vig-toggle-button onLabel="Transit" [formField]="layers.transit" />
      <vig-toggle-button onLabel="Bike lanes" [formField]="layers.bikes" />
    </div>
    <p class="text-sm text-muted-foreground">Visible layers: {{ visible() }}</p>
  `,
})
export class ToggleButtonSignalFormsDemo {
  protected readonly model = signal({ traffic: true, transit: false, bikes: false });
  protected readonly layers = form(this.model);
  protected readonly visible = computed(
    () =>
      Object.entries(this.model())
        .filter(([, on]) => on)
        .map(([name]) => name)
        .join(', ') || 'none',
  );
}
```

## 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-button"][data-part="control"] { … }`: 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-button"]`

| Part | Element | data-state |
| --- | --- | --- |
| `control` | The `<button>` (`aria-pressed`). | `on, off` |
| `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 `<button>` with `aria-pressed`, following the APG toggle button pattern; Enter and Space toggle it.
- With a single label (or a fixed `ariaLabel`) the name stays constant and `aria-pressed` carries the state. When `onLabel` and `offLabel` differ, the changing label is the state, so `aria-pressed` is left off rather than contradicting it.
- Wrap related buttons in an element with `role="group"` and an `aria-label` so the set has a name.
- Hint, disabled reason and error are linked through `aria-describedby`; a touched, invalid button sets `aria-invalid="true"`. `readonly` keeps the button focusable but inert with `aria-disabled="true"` (`aria-readonly` is not valid on buttons).

## API

### ToggleButton

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

A pressed-state button for a boolean choice that reads as an action (PrimeNG p-togglebutton territory). With one label (or an `ariaLabel`) the name stays fixed and `aria-pressed` carries the state; when `onLabel`/`offLabel` differ the changing label is the state, so `aria-pressed` is left off (announcing both would contradict). Readonly keeps the button focusable but inert (`aria-disabled`).

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `ariaLabel` | `string \| undefined` | `undefined` | — |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `name` | `string` | `''` | — |
| `offLabel` | `string \| undefined` | `undefined` | — |
| `onLabel` (required) | `string` | — | Label while pressed; also the fallback when `offLabel` is not set. |
| `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` | — |
