Форми
Form Field
Доступна обгортка поля форми з підписом, підказкою та текстом помилки.
Приклад
Приклад вище — це цей файл, відрендерений наживо:
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();
}
}
Пісочниця
Змінюйте вхідні параметри та взаємодійте з попереднім переглядом: панель подій показує, що випромінює компонент, а код відповідає вашим налаштуванням.
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>Форми та доступність
- Усередині
<volt-form-field>елемент<volt-label>підписує елемент керування черезaria-labelledby, а клік по ньому переводить фокус на елемент керування. Id не потрібні; поза form field використовуйте<volt-label htmlFor>. <volt-hint>завжди входить до опису елемента керування (aria-describedby).<volt-error>додається до опису, поки він відрендерений і валідатори елемента керування не проходять, і зникає з нього після видалення: посилання на видалене повідомлення не лишається.- Без Angular Forms — поле, що валідується сигналами,
<volt-input [state]="invalid() ? 'error' : 'default'" />— немає валідатора, який можна прочитати, тож відрендерений<volt-error>описує елемент керування, доки він є в DOM. Рендерте його під тим самим@if, що й стан помилки. aria-invalid="true"ставиться на сам елемент керування (а не на обгортку), щойно він невалідний і торкнутий, тож помилку передає не лише колір.- Оголошення помилок:
<volt-error>— це сповіщення (alert), яке оголошується в момент вставлення. Рендеріть його, коли користувач покинув поле або надіслав форму (@if (control.touched && control.invalid)), як у прикладі, а не на кожне натискання клавіші. Для валідації, що має чекати, поки користувач покине поле, використовуйтеupdateOn: 'blur'з Angular. - Один елемент керування на form field. Працює з
volt-input,volt-textarea,volt-selectі нативними елементами зngpInput.
Довідник API
VoltError — volt-error
| Вхід | Тип | За замовчуванням |
|---|---|---|
| class | string | '' |
VoltHint — volt-hint
| Вхід | Тип | За замовчуванням |
|---|---|---|
| class | string | '' |
VoltLabel — volt-label
| Вхід | Тип | За замовчуванням |
|---|---|---|
| error | boolean | false |
| htmlFor | string | '' |
| class | string | '' |
VoltFormField — volt-form-field
| Вхід | Тип | За замовчуванням |
|---|---|---|
| class | string | '' |
Встановлення
Скопіюйте вихідний код у свій проєкт:
npx @voltui/cli add form-field
Або імпортуйте його з пакета:
npm install @voltui/components
Вихідний код
Скопіюйте цей код у свій проєкт. Компонент використовує 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());
});
}
}