# Input chips

A text field that turns what is typed into removable chips: tags, keywords or e-mail recipients. Its value is the list of entries.

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

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

## Basic

Enter or a comma turns the text into a chip; `[(value)]` holds the entries as a `string[]`. Entries are trimmed and a duplicate stays in the field as typed, with a message (`allowDuplicates` accepts it; `entryKey` decides what counts as the same entry, by default the text in Unicode NFC). Only the entry a typed separator ends is added; the rest of the field is left as it is. Backspace in the empty field steps onto the last chip, the arrow keys move between chips, and Backspace or Delete removes the focused one.

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

@Component({
  selector: 'app-input-chips-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, InputChips],
  template: `
    <div class="flex w-full max-w-sm flex-col gap-3">
      <vig-input-chips label="Tags" placeholder="Type and press Enter" [(value)]="tags" clearable />
      <p class="text-sm text-muted-foreground">Value: {{ tags() | json }}</p>
    </div>
  `,
})
export class InputChipsBasicDemo {
  protected readonly tags = signal<string[]>(['angular', 'signals']);
}
```

## Separators, limits and validation

`separators` lists the characters that end an entry as it is typed or pasted (a comma by default); a paste of several lines adds each line. `maxLength` stops at a count, `validator` returns `true`, `false` or a message, and `addOnBlur` adds the text when focus leaves. Rejected entries stay in the field and the message shows under it.

```typescript title="input-chips-recipients.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { InputChips, type InputChipsValidator } from '@vigdx/ui/input-chips';

@Component({
  selector: 'app-input-chips-recipients',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputChips],
  template: `
    <div class="w-full max-w-sm">
      <vig-input-chips
        label="To"
        hint="Up to five addresses; paste a list to add them all."
        addOnBlur
        [separators]="separators"
        [maxLength]="5"
        [validator]="email"
        [(value)]="recipients"
      />
    </div>
  `,
})
export class InputChipsRecipientsDemo {
  protected readonly separators = [',', ';', ' '];
  protected readonly recipients = signal<string[]>(['ada@example.com']);
  // `true` accepts; a string rejects with that message (`false` uses labels.invalidLabel).
  protected readonly email: InputChipsValidator = (entry) =>
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(entry) || `${entry} is not an e-mail address.`;
}
```

## Signal Forms

Bind an array field with `[formField]`. Counts are `minLength` and `maxLength` on the array; a schema's `maxLength` also binds the field's own, so further entries are refused as they are typed.

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

@Component({
  selector: 'app-input-chips-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, InputChips],
  template: `
    <div class="max-w-sm">
      <vig-input-chips label="Keywords" hint="Two to four keywords." [formField]="f.keywords" />
    </div>
  `,
})
export class InputChipsSignalFormsDemo {
  private readonly model = signal<{ keywords: string[] }>({ keywords: [] });
  // Arrays express counts with minLength and maxLength; maxLength also stops typing more.
  protected readonly f = form(this.model, (path) => {
    minLength(path.keywords, 2, { message: 'Add at least two keywords.' });
    maxLength(path.keywords, 4);
  });
}
```

## Reactive Forms

Import `VigValueAccessor` next to the field for `formControlName`, `formControl` and `ngModel`. A reset writes `[]` and drops the typed text.

```typescript title="input-chips-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 { VigValueAccessor } from '@vigdx/ui/core';
import { InputChips } from '@vigdx/ui/input-chips';

@Component({
  selector: 'app-input-chips-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, Button, InputChips, VigValueAccessor],
  template: `
    <form
      class="flex max-w-sm flex-col gap-4"
      [formGroup]="form"
      (ngSubmit)="form.markAllAsTouched()"
    >
      <vig-input-chips label="Skills" formControlName="skills" />
      <div class="flex gap-2">
        <vig-button type="submit" label="Save" />
        <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 InputChipsReactiveFormsDemo {
  protected readonly form = new FormGroup({
    // Validators.required treats an empty array as missing.
    skills: new FormControl<string[]>([], { nonNullable: true, validators: Validators.required }),
  });
}
```

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

| Part | Element | data-state |
| --- | --- | --- |
| `field` | Positioned wrapper of the label, the box and the clear button. |   |
| `label` | The visible (or floating) `<label>`. |   |
| `control` | The bordered box holding the chips and the text field. |   |
| `chip` | A `vig-chip` per entry; style its own parts (`data-scope="chip"`). |   |
| `input` | The native text `<input>`. |   |
| `clear` | The clear button (`clearable`). |   |
| `status` | The visually hidden `role="status"` region announcing changes. |   |
| `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

- The field is a native text input with a `<label>`; it is described by the entries (read after its name), the hint and the error. Each chip is a `vig-chip` whose remove button is named "Remove" and the entry.
- Additions, removals and rejections are announced through a polite status region (one message for a paste of several entries).
- Typing with an input method (Japanese, Chinese, Korean…) is never split or committed while a composition is open: Enter confirms the composition, not the entry.
- The field is the only Tab stop: Backspace in the empty field, or the arrow keys at its start (mirrored in right-to-left pages), move onto the chips' remove buttons, and the arrow keys, Home and End move between them. Removing with a key moves on to the next chip; removing with the pointer keeps focus in the field.
- Texts are translated with the locale or per instance through `labels` (`removeAriaLabel`, `clearAriaLabel`, the announcements and the duplicate, limit and invalid messages).

## API

### InputChips

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

A text field that turns what is typed into removable chips, for tags, e-mail recipients or keywords. Enter, a `separators` character (a comma by default) or a paste of several lines adds entries; Backspace in the empty field steps onto the last chip, and the arrow keys move between chips, where Backspace or Delete removes one. The value is the entries, in order.

**Example :**

```html
<vig-input-chips label="Tags" [formField]="form.tags" />
```

Entries are trimmed; duplicates, entries past `maxLength` and entries the `validator` rejects stay in the field with a message. Typing with an IME is never split mid-composition. Additions and removals are announced politely. Works with Signal Forms and, through `VigValueAccessor`, with Reactive Forms and `ngModel`. A schema's `maxLength` stops further entries; `minLength` and `required` validate the array as usual.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `addOnBlur` | `boolean` | `false` | Leaving the field adds what was typed (when it is accepted). |
| `allowDuplicates` | `boolean` | `false` | Accepts an entry that is already a chip (compared by `entryKey`). |
| `clearable` | `boolean` | `false` | Shows a button that removes every chip. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `entryKey` | `(entry: string) => string` | `nfc` | What makes two entries the same for the duplicate check, e.g. `(entry) => entry.toLocaleLowerCase()`. By default the trimmed text in Unicode NFC, so "é" typed or pasted in either form is one entry. |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Visually hides the label, which still names the field; pair it with a placeholder. |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `labelPosition` | `LabelPosition` | `'float'` | `float` (default) rests the label inside the field; `top` sets it above. |
| `labels` | `Partial<InputChipsLabels>` | — | Texts (i18n); locale defaults. |
| `maxLength` | `number \| undefined` | `undefined` | At most this many entries; further ones stay in the field with a message. The Signal Forms name of the array's length limit, so a schema's `maxLength(path, n)` binds it. |
| `name` | `string` | `''` | — |
| `pending` | `boolean` | `false` | — |
| `placeholder` | `string \| undefined` | `undefined` | Shown in the empty field while there are no chips. |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `separators` | `readonly string[]` | `[',']` | Characters that end an entry as it is typed or pasted, besides Enter. |
| `size` | `FieldSize` | `'md'` | — |
| `touched` | `boolean` | `false` | — |
| `validator` | `InputChipsValidator \| undefined` | `undefined` | Checks each entry before it becomes a chip; see `InputChipsValidator`. |
| `value` (model) | `string[]` | `[]` | The entries, in order; `[]` when empty. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `touch` | `void` | — |
| `valueChange` | `string[]` | The entries, in order; `[]` when empty. |

#### 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` | Drops typed text and messages; see `VigFormField.reset`. |
