Forms
Form Field
Accessible form wrapper with label, hint, and error text.
Example
The example above is this file, rendered live:
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import {
VoltError,
VoltFormField,
VoltHint,
VoltInput,
VoltLabel,
VoltNativeButton,
} from '@voltui/components';
/**
* Errors render once a field is touched (left, or the form submitted), so the alert is announced
* then and not on every keystroke.
*/
@Component({
selector: 'app-form-field-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
ReactiveFormsModule,
VoltFormField,
VoltLabel,
VoltHint,
VoltError,
VoltInput,
VoltNativeButton,
],
template: `
<form class="mx-auto max-w-sm space-y-4" [formGroup]="login" (ngSubmit)="submit()" novalidate>
<volt-form-field>
<volt-label>Work email</volt-label>
<volt-input formControlName="email" type="email" autocomplete="email" required />
<volt-hint>We only use it for account updates.</volt-hint>
@if (login.controls.email.touched && login.controls.email.invalid) {
<volt-error>Enter a valid email address.</volt-error>
}
</volt-form-field>
<volt-form-field>
<volt-label>Password</volt-label>
<volt-input
formControlName="password"
type="password"
autocomplete="current-password"
required
/>
<volt-hint>At least 8 characters.</volt-hint>
@if (login.controls.password.touched && login.controls.password.invalid) {
<volt-error>Use at least 8 characters.</volt-error>
}
</volt-form-field>
<button voltButton type="submit" class="w-full">Sign in</button>
</form>
`,
})
export class FormFieldExample {
readonly login = new FormGroup({
email: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
}),
password: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(8)],
}),
});
submit(): void {
// Shows every error at once; a real form would send the value when it is valid.
this.login.markAllAsTouched();
}
}
Playground
Change the inputs and interact with the preview: the events panel shows what the component emits, and the code follows your settings.
volt-form-field
status: INVALID · touched: false
- statusChange
"INVALID"
HTML
<volt-form-field>
<volt-label>Work email</volt-label>
<volt-input [formControl]="email" type="email" required />
<volt-hint>We only use it for account updates.</volt-hint>
@if (email.touched && email.invalid) {
<volt-error>Enter a valid email address.</volt-error>
}
</volt-form-field>Forms and accessibility
- Inside
<volt-form-field>,<volt-label>labels the control througharia-labelledby, and clicking it focuses the control. No ids are needed; outside a form field, use<volt-label htmlFor>. <volt-hint>is always part of the control's description (aria-describedby).<volt-error>joins the description while it is rendered and the control's validators fail, and leaves it when it is removed: no reference to a removed message is left behind.- Without Angular Forms — a field validated with signals,
<volt-input [state]="invalid() ? 'error' : 'default'" />— there is no validator to read, so a rendered<volt-error>describes the control for as long as it is in the DOM. Render it under the same@ifas the error state. aria-invalid="true"is set on the control (not on a wrapper) once it is invalid and touched, so the error is not conveyed by color alone.- Error announcement:
<volt-error>is an alert, announced when it is inserted. Render it once the field has been left or the form submitted (@if (control.touched && control.invalid)), as in the example, rather than on every keystroke. For validation that should wait until the reader leaves the field, use Angular'supdateOn: 'blur'. - One control per form field. Works with
volt-input,volt-textarea,volt-selectand native controls withngpInput.
API Reference
VoltError — volt-error
| Input | Type | Default |
|---|---|---|
| class | string | '' |
VoltHint — volt-hint
| Input | Type | Default |
|---|---|---|
| class | string | '' |
VoltLabel — volt-label
| Input | Type | Default |
|---|---|---|
| error | boolean | false |
| htmlFor | string | '' |
| class | string | '' |
VoltFormField — volt-form-field
| Input | Type | Default |
|---|---|---|
| class | string | '' |
Installation
Copy the source into your project:
npx @voltui/cli add form-field
Or import it from the package:
npm install @voltui/components
Source
Copy this code to your project. The component uses ng-primitives/form-field.
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
import { NgpFormField } from 'ng-primitives/form-field';
import { cn } from '../../utils';
@Component({
selector: 'volt-form-field',
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [NgpFormField],
host: {
'[class]': 'classes()',
},
template: `<ng-content />`,
})
export class VoltFormField {
readonly class = input<string>('');
protected readonly classes = computed(() => cn('space-y-stack w-full block', this.class()));
}
import {
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
input,
} from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { injectFormFieldState, NgpLabel } from 'ng-primitives/form-field';
import { forwardClassFromHost } from '../../host-forwarding';
import { cn } from '../../utils';
/**
* Renders a native `<label>`. Inside `<volt-form-field>` it is wired to the field's control
* automatically; elsewhere pass `htmlFor`. `class` is applied to the `<label>`.
*/
@Component({
selector: 'volt-label',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgpLabel, NgTemplateOutlet],
template: `
<!--
NgpLabel owns the label inside a form field (id, for, aria-labelledby on the control).
Outside one it has no control to point at: it would drop the for attribute and cancel the
native click, so a plain label with htmlFor is rendered instead.
-->
@if (formField()) {
<!-- eslint-disable-next-line @angular-eslint/template/label-has-associated-control -->
<label ngpLabel [class]="classes()">
<ng-container [ngTemplateOutlet]="content" />
</label>
} @else {
<label [class]="classes()" [attr.for]="htmlFor() || null">
<ng-container [ngTemplateOutlet]="content" />
</label>
}
<ng-template #content><ng-content /></ng-template>
`,
})
export class VoltLabel {
protected readonly formField = injectFormFieldState({ optional: true });
readonly error = input<boolean, unknown>(false, { transform: booleanAttribute });
readonly htmlFor = input<string>('');
readonly class = input<string>('');
protected readonly classes = computed(() =>
cn(
'text-sm font-medium text-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
this.error() && 'text-error',
this.class()
)
);
constructor() {
forwardClassFromHost();
}
}
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
import { NgpDescription } from 'ng-primitives/form-field';
import { forwardClassFromHost } from '../../host-forwarding';
import { cn } from '../../utils';
/** Field description, referenced by the control's `aria-describedby`. `class` styles the text. */
@Component({
selector: 'volt-hint',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgpDescription],
template: `
<span ngpDescription [class]="classes()">
<ng-content />
</span>
`,
})
export class VoltHint {
readonly class = input<string>('');
protected readonly classes = computed(() => cn('text-sm text-muted-foreground', this.class()));
constructor() {
forwardClassFromHost();
}
}
import {
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
effect,
inject,
input,
viewChild,
} from '@angular/core';
import { injectFormFieldState, NgpError } from 'ng-primitives/form-field';
import { forwardClassFromHost } from '../../host-forwarding';
import { cn } from '../../utils';
/**
* Validation message. It is an alert, so a screen reader announces it when it is *inserted*: render it
* once the field has been left or the form submitted (`@if (control.touched && control.invalid)`),
* not on every keystroke. While it is rendered and its validator fails, the field's control lists it
* in `aria-describedby`. `class` styles the text.
*
* Without Angular Forms — a field validated with signals, `<volt-input [state]="…">` — nothing reports a
* failing validator, so being rendered is the signal: the message describes the control for as long as
* it is in the DOM.
*/
@Component({
selector: 'volt-error',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgpError],
template: `
<span ngpError role="alert" aria-live="assertive" [class]="classes()">
<ng-content />
</span>
`,
})
export class VoltError {
readonly class = input<string>('');
protected readonly classes = computed(() => cn('text-error text-sm font-medium', this.class()));
private readonly formField = injectFormFieldState({ optional: true });
private readonly error = viewChild.required(NgpError);
constructor() {
forwardClassFromHost();
// ng-primitives unregisters an error on destroy only if it is still failing. An error removed
// because the value became valid is destroyed in the same pass that clears the failure, so its
// id stayed in the control's aria-describedby, pointing at an element that no longer exists.
inject(DestroyRef).onDestroy(() => this.formField()?.removeDescription(this.error().id()));
// With a Forms control the field's status is known (`invalid()` is a boolean) and ngpError registers
// the message itself while its validator fails. Without one it stays `null` and nobody would.
effect(() => {
const field = this.formField();
if (field && field.invalid() === null) field.addDescription(this.error().id());
});
}
}