Formularios
Form Field
Envoltorio de formulario accesible con etiqueta, pista y texto de error.
Ejemplo
El ejemplo de arriba es este archivo, renderizado en vivo:
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();
}
}
Zona de pruebas
Cambia los inputs e interactúa con la vista previa: el panel de eventos muestra lo que emite el componente y el código sigue tus ajustes.
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>Formularios y accesibilidad
- Dentro de
<volt-form-field>,<volt-label>etiqueta el control mediantearia-labelledby, y al pulsarla se enfoca el control. No hacen falta ids; fuera de un form field, usa<volt-label htmlFor>. <volt-hint>forma siempre parte de la descripción del control (aria-describedby).<volt-error>entra en la descripción mientras está renderizado y fallan los validadores del control, y sale de ella al eliminarse: no queda ninguna referencia a un mensaje eliminado.- Sin Angular Forms —un campo validado con signals,
<volt-input [state]="invalid() ? 'error' : 'default'" />— no hay validador que leer, así que un<volt-error>renderizado describe el control mientras está en el DOM. Renderízalo bajo el mismo@ifque el estado de error. aria-invalid="true"se pone en el control (no en un envoltorio) en cuanto es inválido y está tocado, así que el error no se transmite solo con el color.- Anuncio de errores:
<volt-error>es una alerta que se anuncia al insertarse. Renderízalo cuando el usuario haya salido del campo o enviado el formulario (@if (control.touched && control.invalid)), como en el ejemplo, y no en cada pulsación. Para una validación que deba esperar a que el usuario salga del campo, usaupdateOn: 'blur'de Angular. - Un control por form field. Funciona con
volt-input,volt-textarea,volt-selecty controles nativos conngpInput.
Referencia de la API
VoltError — volt-error
| Entrada | Tipo | Por defecto |
|---|---|---|
| class | string | '' |
VoltHint — volt-hint
| Entrada | Tipo | Por defecto |
|---|---|---|
| class | string | '' |
VoltLabel — volt-label
| Entrada | Tipo | Por defecto |
|---|---|---|
| error | boolean | false |
| htmlFor | string | '' |
| class | string | '' |
VoltFormField — volt-form-field
| Entrada | Tipo | Por defecto |
|---|---|---|
| class | string | '' |
Instalación
Copia el código en tu proyecto:
npx @voltui/cli add form-field
O impórtalo desde el paquete:
npm install @voltui/components
Código fuente
Copia este código en tu proyecto. El componente usa 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());
});
}
}