# Checkbox

A labelled checkbox for a yes/no choice that takes effect when the form is submitted, such as accepting terms or opting in. For settings that apply at once, use a toggle switch.

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

```typescript title="Import"
import { Checkbox } from '@vigdx/ui/checkbox';
```

## Basic

Bind `[(value)]` to a boolean signal. The whole label is clickable; `hint` adds help text below it.

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

@Component({
  selector: 'app-checkbox-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Checkbox],
  template: `
    <div class="flex flex-col gap-3">
      <vig-checkbox label="Remember me on this device" [(value)]="remember" />
      <vig-checkbox
        label="Weekly digest"
        hint="One email every Monday, unsubscribe at any time."
        [(value)]="digest"
      />
    </div>
    <p class="text-sm text-muted-foreground">Remember: {{ remember() }} · Digest: {{ digest() }}</p>
  `,
})
export class CheckboxBasicDemo {
  protected readonly remember = signal(true);
  protected readonly digest = signal(false);
}
```

## States

`disabled` greys out box and label. `readonly` keeps the box focusable but ignores clicks and Space. `required` adds an asterisk to the label.

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

@Component({
  selector: 'app-checkbox-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Checkbox],
  template: `
    <div class="grid gap-3 sm:grid-cols-2">
      <vig-checkbox label="Unchecked" />
      <vig-checkbox label="Checked" [value]="true" />
      <vig-checkbox label="Disabled" [disabled]="true" />
      <vig-checkbox label="Disabled and checked" [value]="true" [disabled]="true" />
      <vig-checkbox label="Read-only" [value]="true" [readonly]="true" />
      <vig-checkbox label="Required" [required]="true" />
    </div>
  `,
})
export class CheckboxStatesDemo {}
```

## Error

Errors show once the checkbox is `touched` and `invalid`; the box turns red and the message appears below. `errorMessages` replaces the built-in text for each error kind.

```typescript title="checkbox-error.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Checkbox } from '@vigdx/ui/checkbox';

@Component({
  selector: 'app-checkbox-error',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Checkbox],
  template: `
    <vig-checkbox
      label="I accept the terms of service"
      [required]="true"
      [touched]="true"
      [invalid]="true"
      [errors]="[{ kind: 'required' }]"
      [errorMessages]="{ required: 'Accept the terms to continue.' }"
    />
  `,
})
export class CheckboxErrorDemo {}
```

## Hidden label

In a table or matrix where the headers already name each column, `hideLabel` hides the label text but keeps it as the accessible name. Make each label unique, for example by including the row name.

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

@Component({
  selector: 'app-checkbox-hidden-label',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Checkbox],
  template: `
    <table class="w-full max-w-md text-sm">
      <caption class="sr-only">
        Notification channels
      </caption>
      <thead>
        <tr class="border-b border-border text-start text-muted-foreground">
          <th scope="col" class="py-2 text-start font-medium">Event</th>
          <th scope="col" class="py-2 font-medium">Email</th>
          <th scope="col" class="py-2 font-medium">Push</th>
        </tr>
      </thead>
      <tbody>
        @for (event of events; track event) {
          <tr class="border-b border-border-subtle">
            <th scope="row" class="py-2 text-start font-normal">{{ event }}</th>
            <td class="py-2 text-center">
              <vig-checkbox class="inline-block" [label]="event + ' by email'" [hideLabel]="true" />
            </td>
            <td class="py-2 text-center">
              <vig-checkbox
                class="inline-block"
                [label]="event + ' as push notification'"
                [hideLabel]="true"
                [value]="true"
              />
            </td>
          </tr>
        }
      </tbody>
    </table>
  `,
})
export class CheckboxHiddenLabelDemo {
  protected readonly events = ['New comment', 'Mention', 'Weekly report'];
}
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`. Use `Validators.requiredTrue` for a box that must be checked.

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

@Component({
  selector: 'app-checkbox-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, Button, Checkbox, VigValueAccessor],
  template: `
    <form class="flex flex-col gap-4" [formGroup]="form" (ngSubmit)="submit()">
      <div class="flex flex-col gap-3">
        <vig-checkbox label="Send me product updates" formControlName="updates" />
        <vig-checkbox label="I accept the privacy policy" formControlName="privacy" />
      </div>
      <div class="flex gap-2">
        <vig-button type="submit" label="Continue" />
        <vig-button label="Reset" variant="secondary" (click)="form.reset()" />
      </div>
      <pre class="rounded-input bg-subtle p-3 font-mono text-xs">{{ form.value | json }}</pre>
    </form>
  `,
})
export class CheckboxReactiveFormsDemo {
  protected readonly form = new FormGroup({
    updates: new FormControl(false, { nonNullable: true }),
    // requiredTrue: an unchecked box is invalid.
    privacy: new FormControl(false, { nonNullable: true, validators: Validators.requiredTrue }),
  });

  protected submit(): void {
    this.form.markAllAsTouched();
  }
}
```

## Signal Forms

`vig-checkbox` implements `FormValueControl<boolean>`. Signal Forms' `required()` treats `false` as empty, so it makes the box mandatory.

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

@Component({
  selector: 'app-checkbox-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, Checkbox],
  template: `
    <div class="flex flex-col gap-3">
      <vig-checkbox label="Send me product updates" [formField]="consent.updates" />
      <vig-checkbox label="I accept the terms of service" [formField]="consent.terms" />
    </div>
    <p class="text-sm text-muted-foreground">Valid: {{ consent().valid() ? 'yes' : 'no' }}</p>
  `,
})
export class CheckboxSignalFormsDemo {
  protected readonly model = signal({ updates: false, terms: false });
  // required() treats false as empty, so the terms box must be checked.
  protected readonly consent = form(this.model, (path) => {
    required(path.terms);
  });
}
```

## 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="checkbox"][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="checkbox"]`

| Part | Element | data-state |
| --- | --- | --- |
| `root` | The `<label>` wrapping box and text. | `checked, unchecked, indeterminate` |
| `control` | Wrapper of the box and its check mark. |   |
| `input` | The native checkbox (the visible box). |   |
| `indicator` | The check mark or indeterminate dash. |   |
| `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 `<input type="checkbox">` inside its `<label>`: Space toggles it and the label text is its accessible name.
- `label` is required. With `hideLabel` the text is visually hidden but still read out, so keep it descriptive.
- Hint, disabled reason and error are linked through `aria-describedby`; a touched, invalid box sets `aria-invalid="true"`.
- Native checkboxes have no read-only state, so `readonly` reverts each change and sets `aria-readonly="true"`; tell users why the box cannot be changed, for example in the `hint`.
- `indeterminate` sets the native mixed state, announced as "mixed" or "partially checked"; the next click clears it.
- The box scales with the font size (1.25em) and shows a focus ring on keyboard focus.

## API

### Checkbox

Selector: `vig-checkbox` · 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` | — |
| `indeterminate` (model) | `boolean` | `false` | Mixed state, e.g. a "select all" whose items are partly selected. Sets the native `indeterminate` property (exposed as `aria-checked="mixed"`) and draws a dash; the browser clears it on the next click, which this model mirrors. |
| `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 |
| --- | --- | --- |
| `indeterminateChange` | `boolean` | Mixed state, e.g. a "select all" whose items are partly selected. Sets the native `indeterminate` property (exposed as `aria-checked="mixed"`) and draws a dash; the browser clears it on the next click, which this model mirrors. |
| `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` | — |
