# Input OTP

A one-time code or PIN entered in boxes. The boxes are drawn over one native input, so SMS autofill, paste and screen readers see a single field.

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

```typescript title="Import"
import { InputOtp } from '@vigdx/ui/input-otp';
```

## Basic

Bind `[(value)]` to a string signal. Typing fills the next box, and `(completed)` fires with the code once the last box is filled: verify it there. Pasting a whole code into any box fills them all.

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

@Component({
  selector: 'app-input-otp-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputOtp],
  template: `
    <vig-input-otp
      label="Verification code"
      hint="Enter the 6-digit code we sent to your phone."
      [(value)]="code"
      (completed)="verified.set($event)"
    />
    <p class="text-sm text-muted-foreground" role="status">
      @if (verified()) {
        Checking {{ verified() }}…
      } @else {
        {{ code().length }} of 6 digits entered.
      }
    </p>
  `,
})
export class InputOtpBasicDemo {
  protected readonly code = signal('');
  protected readonly verified = signal('');
}
```

## PINs, groups and letters

`length` sets the number of boxes (6 by default). `masked` draws dots instead of the characters for PINs; the input stays a text field (so password managers leave it alone) and `autocomplete` defaults to `off`, since a PIN is not a code sent by SMS. `groupSize` draws a separator, e.g. `3` for 123–456. `charset="alphanumeric"` takes letters and digits and opens the upper-case text keyboard instead of the digit pad. Other characters are dropped, so a pasted `123-456` gives `123456`; an alphanumeric code keeps its letters, so strip prefixes such as `G-` before passing it in.

```typescript title="input-otp-variants.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { InputOtp } from '@vigdx/ui/input-otp';

@Component({
  selector: 'app-input-otp-variants',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputOtp],
  template: `
    <div class="grid gap-6 sm:grid-cols-2">
      <vig-input-otp label="PIN" masked [length]="4" hint="Four digits, hidden as you type." />
      <vig-input-otp label="Grouped" [groupSize]="3" />
      <vig-input-otp
        label="Recovery code"
        charset="alphanumeric"
        [length]="8"
        [groupSize]="4"
        autocomplete="off"
      />
      <vig-input-otp label="Small" size="sm" [length]="4" />
    </div>
  `,
})
export class InputOtpVariantsDemo {}
```

## States and sizes

`disabled`, `readonly` and errors work as in the other fields; the boxes of an invalid field turn red and the message is linked to the input. `size` is `sm`, `md` (default) or `lg`; the boxes scale with the font and shrink to fit narrow screens.

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

@Component({
  selector: 'app-input-otp-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputOtp],
  template: `
    <div class="grid gap-6 sm:grid-cols-2">
      <vig-input-otp label="Disabled" value="123" disabled />
      <vig-input-otp label="Read-only" value="123456" readonly />
      <vig-input-otp
        label="Expired code"
        value="123456"
        [touched]="true"
        [invalid]="true"
        [errors]="errors"
      />
      <vig-input-otp label="Large" size="lg" [length]="4" />
    </div>
  `,
})
export class InputOtpStatesDemo {
  protected readonly errors = [{ kind: 'expired', message: 'This code has expired.' }];
}
```

## Signal Forms

`vig-input-otp` implements `FormValueControl<string>`, so `[formField]` binds value, validation, `required`, `disabled` and `readonly`. The value is the code as typed: check its length with `minLength`. A value set from outside is cleaned up and written back (`12a-456` becomes `12456`, a shorter `length` cuts it): Reactive Forms and `ngModel` controls stay pristine, but Signal Forms only takes values from a control as edits, so there the field turns dirty. Set clean values to avoid that.

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

@Component({
  selector: 'app-input-otp-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, InputOtp],
  template: `
    <vig-input-otp label="Code" [formField]="verification.code" />
    <p class="text-sm text-muted-foreground">Valid: {{ verification().valid() ? 'yes' : 'no' }}</p>
  `,
})
export class InputOtpSignalFormsDemo {
  protected readonly model = signal({ code: '' });
  protected readonly verification = form(this.model, (path) => {
    required(path.code);
    minLength(path.code, 6, { message: 'Enter all 6 digits.' });
  });
}
```

## Reactive Forms

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

```typescript title="input-otp-reactive-forms.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { Button } from '@vigdx/ui/button';
import { VigValueAccessor } from '@vigdx/ui/core';
import { InputOtp } from '@vigdx/ui/input-otp';

@Component({
  selector: 'app-input-otp-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReactiveFormsModule, Button, InputOtp, VigValueAccessor],
  template: `
    <form class="flex flex-col gap-4" (ngSubmit)="submit()">
      <vig-input-otp label="PIN" masked [length]="4" [formControl]="pin" />
      <div class="flex items-center gap-3">
        <vig-button type="submit" label="Unlock" />
        <span class="text-sm text-muted-foreground" role="status">{{ status() }}</span>
      </div>
    </form>
  `,
})
export class InputOtpReactiveFormsDemo {
  protected readonly pin = new FormControl('', {
    nonNullable: true,
    validators: [Validators.required, Validators.minLength(4)],
  });
  protected readonly status = signal('');

  protected submit(): void {
    this.pin.markAsTouched();
    this.status.set(this.pin.valid ? 'Unlocked.' : '');
  }
}
```

## SMS autofill

- The field is one `<input autocomplete="one-time-code" inputmode="numeric">`, the markup iOS Safari and Android Chrome need to offer the code from an SMS above the keyboard. Split inputs (one per digit) break that autofill, paste and screen readers, which is why the boxes are only drawn.
- End the SMS with a line binding the code to your domain, `@example.com #123456`, so the browser only offers it on your site.
- `webOtp` also asks the WebOTP API for the code where it exists (Chrome on Android): the browser reads the SMS and, once the user agrees, fills the field and fires `(completed)`. The request stops when the field is destroyed, disabled or `webOtp` turns off.

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

| Part | Element | data-state |
| --- | --- | --- |
| `label` | The visible label, above the boxes. |   |
| `field` | The LTR row holding the boxes and the input. |   |
| `cells` | The boxes, hidden from assistive technology. |   |
| `cell` | One box: `active` under the caret or selection, else `filled` or `empty`. | `active, filled, empty` |
| `caret` | The caret drawn in the active empty box. |   |
| `separator` | The dash between groups (`groupSize`). |   |
| `input` | The native `<input>` over the boxes, holding the code. |   |
| `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

- Screen readers meet one text field named by its `<label>` and described by the expected length ("6 digits", from `labels.lengthAriaLabel`), then the hint and error. The boxes are hidden from assistive technology; the code reads as one value.
- Keyboard: typing fills the next box and overwrites a selected one; Backspace removes the character before the caret (or the selected one); Arrow Left/Right, Home and End move between boxes, never past the first empty one. Shift+arrows and select-all work as in any text field.
- The active box shows a 2px outline (Highlight in forced-colors mode) and an empty one a caret, which only blinks without `prefers-reduced-motion`.
- With `masked`, the boxes show dots but screen readers still read the code, as they do a revealed password: the field never becomes a password input, which would invite password managers to save the PIN.
- IME input (full-width digits from a Japanese keyboard, Arabic-Indic digits) is accepted and folded to ASCII when the composition ends.
- The boxes always run left to right, also on RTL pages: codes are read in that order. The label, hint and error follow the page direction.

## API

### InputOtp

Selector: `vig-input-otp` · Kind: component

A one-time code or PIN entered in boxes:

**Example :**

```html
<vig-input-otp label="Verification code" (completed)="verify($event)" [(value)]="code" />
```

The boxes are drawn over ONE native `<input>` that holds the whole code, so SMS autofill (`autocomplete="one-time-code"` on iOS Safari and Android Chrome), paste, undo and screen readers all see a single labelled text field, never six. Typing fills the next box and overwrites a selected one; pasting a whole code from any box fills them all. `(completed)` fires when the last box is filled. The boxes always run left to right (`dir="ltr"`), also on RTL pages.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `autocomplete` | `string \| undefined` | `undefined` | Native `autocomplete`: `one-time-code` by default, so iOS and Android offer the code from an SMS; `off` when `masked`, since a PIN is not a code sent to the user. |
| `charset` | `InputOtpCharset` | `'numeric'` | `numeric` (default: digits, the digit keypad) or `alphanumeric` (letters and digits, upper-case keyboard). Other characters are dropped, so a pasted `123-456` gives `123456`; an alphanumeric code keeps letters, so strip prefixes such as `G-` yourself. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `groupSize` | `number` | `0` | Draws a separator after every this many boxes, e.g. `3` for `123–456`; `0` for none. |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Visually hides the label, which still names the field. |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `labels` | `Partial<InputOtpLabels>` | — | Texts (i18n); locale defaults. |
| `length` | `number` | `6` | Number of characters (boxes). |
| `masked` | `boolean` | `false` | Hides the characters behind dots, for PINs. The input stays a text field, so password managers leave it alone; screen readers still read the code, as with a revealed password. |
| `name` | `string` | `''` | — |
| `pending` | `boolean` | `false` | — |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `size` | `FieldSize` | `'md'` | `sm`, `md` (default) or `lg`: the boxes scale with it. |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `string` | `''` | — |
| `webOtp` | `boolean` | `false` | Also asks the WebOTP API for the code (Chrome on Android): the browser reads an SMS ending in `@your.domain #123456` and, once the user agrees, fills the field and fires `(completed)`. Feature-detected; elsewhere the `one-time-code` autofill applies. The request ends once the code is complete, however it was entered. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `completed` | `string` | Emits the code when the user (or WebOTP) fills the last box. |
| `touch` | `void` | — |
| `valueChange` | `string` | — |

#### 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` | — |
