# Field

Connect a form control to its label, description, and validation errors.

A field connects a form control to its label, its description and the errors it shows, and wires up `id`, `for` and `aria-describedby` for you.

```angular-ts title="input.ts"
import { Component } from "@angular/core"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/angular/field"
import { Input } from "@ui-sdk/angular/input"

@Component({
  imports: [Field, FieldDescription, FieldLabel, Input],
  template: `
    <div data-slot="stack">
      <div uiField>
        <label uiFieldLabel>Username</label>
        <input
          uiInput
          name="username"
          placeholder="hollis"
          autocomplete="username"
        />
        <p uiFieldDescription>Choose a unique username for your account.</p>
      </div>
    </div>
  `,
})
class Example {}

export { Example }
```

Press Username to focus the input, then type a name.

## Installation

```bash
npm install @ui-sdk/angular @ui-sdk/core
```

## Composition

Use the following composition to build Field:

```text
uiField
├── uiFieldLabel
├── uiInput
├── uiFieldDescription
└── uiFieldError
```

## Usage

```ts
import { Component } from "@angular/core"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/angular/field"
import { Input } from "@ui-sdk/angular/input"

@Component({
  selector: "app-example",
  imports: [Field, FieldDescription, FieldError, FieldLabel, Input],
  template: `
    <div uiField name="username">
      <label uiFieldLabel>Username</label>
      <input uiInput autocomplete="username" required />
      <p uiFieldDescription>This is your public name.</p>
      <div *uiFieldError></div>
    </div>
  `,
})
class Example {}

export { Example }
```

The control is one of ours, like an [Input](/docs/angular/components/input), a [Textarea](/docs/angular/components/textarea), a [Select](/docs/angular/components/select) or a [Checkbox](/docs/angular/components/checkbox), and it wires itself to the field.

The label names the control, and the description and any error that shows describe it.

Group related fields in a [field set](#field-sets):

```angular-html
<fieldset uiFieldSet>
  <legend uiFieldLegend></legend>
  <p uiFieldDescription></p>
  <div uiFieldGroup>
    <div uiField></div>
    <div uiField></div>
  </div>
</fieldset>
```

## Controls

Use an [Input](/docs/angular/components/input) for a line of text and a [Textarea](/docs/angular/components/textarea) for more:

```angular-html
<div uiField>
  <label uiFieldLabel>Feedback</label>
  <textarea uiTextarea name="feedback"></textarea>
</div>
```

For a control we don't ship, like a native `<select>`, use `uiFieldControl`. Put it on the native element, and it connects it to the field the same way. An [agent](/docs/agents) sees only our components, so it can't fill a `uiFieldControl`: use ours where there is one.

```angular-html
<div uiField>
  <label uiFieldLabel>Department</label>
  <select uiFieldControl name="department">
    <option value="design">Design</option>
    <option value="engineering">Engineering</option>
  </select>
</div>
```

A [Checkbox](/docs/angular/components/checkbox), [Switch](/docs/angular/components/switch) or [Radio Group](/docs/angular/components/radio) inside a field uses the field's label and description. Pressing the label toggles a checkbox or switch. A radio group takes the field's label as its name, and each radio keeps a label of its own:

```angular-html
<div uiField>
  <button uiSwitch name="mfa"></button>
  <label uiFieldLabel>Two-factor authentication</label>
  <p uiFieldDescription>Ask for a code when you sign in.</p>
</div>

<div uiField>
  <label uiFieldLabel>Plan</label>
  <div uiRadioGroup name="plan" defaultValue="monthly">
    <label>
      <button uiRadio value="monthly"></button>
      Monthly
    </label>
    <label>
      <button uiRadio value="yearly"></button>
      Yearly
    </label>
  </div>
</div>
```

## Validation

Use native constraints such as `required`, `type="email"`, and `pattern`. Errors appear after a submit attempt and update as the value changes. The first invalid control takes focus.

Leave an error empty to show the browser's message, or use `match="valueMissing"` and `match="typeMismatch"` for your own messages. Adding an error part replaces the browser's validation bubble with that message in the page.

```angular-ts title="validation.ts"
import { Component } from "@angular/core"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/angular/field"
import { Input } from "@ui-sdk/angular/input"
import { useLog } from "./log"

@Component({
  imports: [Field, FieldDescription, FieldError, FieldLabel, Input],
  template: `
    <form data-slot="stack" (submit)="submit($event)">
      <div uiField #email="uiField" name="email">
        <label uiFieldLabel>Email</label>
        <input uiInput type="email" required placeholder="hollis@example.com" />
        <p uiFieldDescription>
          {{
            email.state().valid
              ? "Looks good."
              : "We'll send you a confirmation link."
          }}
        </p>
        <div uiFieldError match="valueMissing">Enter your email address.</div>
        <div uiFieldError match="typeMismatch">
          Enter an email address like hollis@example.com.
        </div>
      </div>
      <div uiField name="website">
        <label uiFieldLabel>Website</label>
        <input uiInput type="url" required placeholder="https://example.com" />
        <div uiFieldError></div>
      </div>
      <button type="submit" data-variant="solid">Subscribe</button>
    </form>
  `,
})
class Example {
  readonly log = useLog()

  submit(event: SubmitEvent) {
    event.preventDefault()
    const data = new FormData(event.currentTarget as HTMLFormElement)
    this.log(`Subscribed ${data.get("email")}`)
  }
}

export { Example }
```

Press Subscribe with an empty or invalid email, then correct it to clear the error.

## Errors from Your Code

Pass `invalid` when your server or form library supplies an error. `true` shows it immediately. Clear the value to return to the browser's validation.

Give this error its own text and set `match` to `true`. Named matches such as `valueMissing` still refer to native validation. `[invalid]="false"` hides the field's invalid state, but does not make an invalid native control pass validation.

```angular-html
<div uiField name="email" [invalid]="serverError ? true : undefined">
  <label uiFieldLabel>Email</label>
  <input uiInput type="email" required (valueChange)="serverError = null" />
  <div *uiFieldError="'valueMissing'">Enter your email address.</div>
  @if (serverError) {
    <div *uiFieldError="true">{{ serverError }}</div>
  }
</div>
```

## Required and Disabled

A required control marks every part with `data-required`, and the parts' state has `required`, so a label can show a mark with CSS alone.

A disabled field disables its control and marks every part with `data-disabled`, the way a [disabled field set](#disabled-field-sets) does for every field inside it.

## Character Count

Keep the text in state and show its length in the description. Set `maxlength` on the control to enforce the limit.

```angular-html
<div uiField>
  <label uiFieldLabel>Bio</label>
  <textarea uiTextarea [(value)]="bio" maxlength="280"></textarea>
  <p uiFieldDescription>{{ bio().length }} / 280</p>
</div>
```

## Forms

The control submits its value under its own `name`, or the field's name if it has none. Reset restores the control's default and hides validation errors. Disabled controls are left out of the submitted values. See [Forms](/docs/angular/forms) for the shared form behavior.

## Field Sets

A field set groups related fields under a legend, and disables them together.

```angular-ts title="field-set.ts"
import { Component } from "@angular/core"
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "@ui-sdk/angular/field"
import { Input } from "@ui-sdk/angular/input"

@Component({
  imports: [
    Field,
    FieldDescription,
    FieldGroup,
    FieldLabel,
    FieldLegend,
    FieldSet,
    Input,
  ],
  template: `
    <fieldset uiFieldSet>
      <legend uiFieldLegend>Address</legend>
      <p uiFieldDescription>We need your address to deliver your order.</p>
      <div uiFieldGroup>
        <div uiField name="street">
          <label uiFieldLabel>Street address</label>
          <input uiInput autocomplete="street-address" />
        </div>
        <div data-slot="grid">
          <div uiField name="city">
            <label uiFieldLabel>City</label>
            <input uiInput autocomplete="address-level2" />
          </div>
          <div uiField name="postal-code">
            <label uiFieldLabel>Postal code</label>
            <input uiInput autocomplete="postal-code" />
          </div>
        </div>
      </div>
    </fieldset>
  `,
})
class Example {}

export { Example }
```

Move through the address fields. Their legend and description name the group.

`uiFieldSet` is a native `<fieldset>` and `uiFieldLegend` a native `<legend>`, so the set is named, and disabled, before scripts run. Keep the legend the first child. A `uiFieldLegend` on another element, like a `<div>`, still names the set through `aria-labelledby`.

A `uiFieldDescription` right inside the set, outside any `uiField`, describes the set, so screen readers read it as focus enters. `uiFieldGroup` is a `<div>` that stacks the fields, with no role and no state: the field set is what names and disables a group.

## Disabled Field Sets

Disabling the set disables its controls and nested field sets. The form leaves their values out of submissions.

```angular-html
<fieldset uiFieldSet [disabled]="sameAsShipping">
  <legend uiFieldLegend>Billing address</legend>
  <div uiField name="billing-street">
    <label uiFieldLabel>Street address</label>
    <input uiInput autocomplete="billing street-address" />
  </div>
</fieldset>
```

## Groups in a Field Set

The legend names a [checkbox group](/docs/angular/components/checkbox#group) or a [radio group](/docs/angular/components/radio) inside the set, so the group needs no label of its own.

```angular-html
<fieldset uiFieldSet>
  <legend uiFieldLegend>Notifications</legend>
  <div uiCheckboxGroup name="notify" [defaultValue]="['mentions']">
    <label>
      <button uiCheckbox value="mentions"></button>
      Mentions
    </label>
    <label>
      <button uiCheckbox value="follows"></button>
      New followers
    </label>
  </div>
</fieldset>
```

## Custom Rendering

Each directive goes on an element you write, like `uiFieldControl` on a `<select>`. Read the field's state from a template reference:

```angular-html
<div uiField #username="uiField">
  <label uiFieldLabel>Username</label>
  <input uiInput pattern="[a-z0-9]+" />
  <p uiFieldDescription>
    {{
      username.state().invalid
        ? "Use letters and numbers only."
        : "Letters and numbers."
    }}
  </p>
</div>
```

`uiFieldError`'s state also has the `message` for the current problem. Each state is a signal, so the template updates only where it reads a value that changed. Each part's state is listed under [State](#state).

## Custom Controls

A control of your own joins the field around it, the way ours do, when it puts `FieldControl` on its element as a host directive. The field then gives it the `id`, `aria-labelledby`, `aria-describedby` after your own, `aria-invalid`, `disabled` and its data attributes. `useFieldControl()` returns the field's `name()` and `disabled()`, or `undefined` outside a field:

```ts title="phone-input.ts"
import { Directive } from "@angular/core"
import { FieldControl, useFieldControl } from "@ui-sdk/angular/field"

@Directive({
  selector: "input[appPhoneInput]",
  hostDirectives: [FieldControl],
  host: { type: "tel", autocomplete: "tel", "[attr.name]": "field?.name()" },
})
export class PhoneInput {
  readonly field = useFieldControl()
}
```

```angular-html
<div uiField name="phone">
  <label uiFieldLabel>Phone</label>
  <input appPhoneInput required />
  <div uiFieldError></div>
</div>
```

The field reads validity from the native inputs, selects and textareas inside it, so `required` and `pattern` work on the input above. A control that isn't a native input, like a row of buttons, takes part through a native input of its own: ours render one, visually hidden, beside the control.

To build a control from scratch on the primitives ours use, see [Primitives](/docs/core/kernel/define-a-primitive).

## Styling

Use `data-invalid` and `data-valid` for validation, and `data-focused`, `data-required` and `data-disabled` for the rest. Every part of a field gets the same attributes, so a label can turn red with its control.

Each part has a `data-slot`, such as `field-label`, and its state attributes are listed under [Data Attributes](#data-attributes).

## Data Attributes

### Field
`[data-slot="field"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldLabel
`[data-slot="field-label"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldControl
`[data-slot="field-control"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldDescription
`[data-slot="field-description"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldError
`[data-slot="field-error"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldSet
`uiFieldGroup` has `data-slot="field-group"` and no state attributes.

`[data-slot="field-set"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### FieldLegend
`[data-slot="field-legend"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### FieldDescription in a FieldSet
`[data-slot="field-description"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

## API Reference

Each option below is an input on the directive.

A field has no change events. Read its state from the parts' data attributes, or from a part's `state()`. Set `debug` to log every state change and its reason.

### Field

- `name?` (`string`): The name the control submits under, when the control doesn't set its own.
- `disabled?` (`boolean`): Disables the control, and marks every part.
- `invalid?` (`boolean`): Whether the field shows as invalid, when your code decides, like a form library or an error from the server. `true` shows its errors now, `false` shows none whatever the browser thinks. Leave it out to show the browser's own validation once a submit finds the field invalid.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### FieldError

- `match?` (`boolean | ValidityKey`): When this error shows. `true` shows it always and `false` never. A validity flag, like `"valueMissing"`, shows it only for that problem of the browser's own validation. Without it, any problem shows it.

### FieldSet

- `disabled?` (`boolean`): Disables every control inside it, except those in its legend, and leaves them out of the form.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### State

- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.
- `message` (`string`): The browser's message for the current problem. Children you pass show instead.

A `uiFieldDescription` receives the field's state, or only `disabled` when it describes a field set.

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it. Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean | undefined`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean | undefined`): Whether focus is inside the control.
- `invalid` (`boolean | undefined`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean | undefined`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

Every part of a field set receives the same state.

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it.

## Accessibility

The label names the control with `aria-labelledby`, beside a native `<label for>` where the control can take one. The description and any error that shows describe it with `aria-describedby`, and an invalid control has `aria-invalid`. The tests below cover these connections and keyboard behavior.

**Labelling**

- The label names the control.
- The description describes the control.
- Clicking the label of a text field focuses it.

**A label wrapping a field**

- Names the control inside it.
- Checks its control when clicked anywhere.
- Keeps the field's description on its control.
- Names a control that renders after it.
- Keeps the part's data-slot.
- Warns in development only when a label outside a field labels nothing.
- A description and an error outside a field keep their data-slot. Web components only.
- A hidden error outside a field stays hidden whatever display its class gives. Web components only.
- An error outside a field follows its match. Web components only.
- An error outside a field shows a child that arrives after it. Web components only.

**Errors**

- Stay hidden until the form tries to submit.
- Show the browser's message when they have no text of their own.
- Count another library's form-associated element inside the field.
- Describe the control while they show.
- Update as the value changes once shown.
- Update as state set from script changes the value once shown. Web components only.
- A field marked invalid shows its error right away.
- A field marked valid never shows the browser's errors.
- A form reset hides them again.
- Errors in the page replace the browser's message, and the first invalid control takes focus.

Runs in React, Vue and web components.

In a field set:

- The legend names the group.
- A disabled field set disables the controls inside and leaves them out of the form.
- Enabling it again restores the controls.
- A field set disabled from the start disables its required fields.
- Fields in a disabled field set mark their parts disabled.

**Enhancements**

- The description describes the group.

Runs in React, Vue and web components.

In a form:

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React, Vue and web components.
