Formularios
Input y formularios
Muestra un campo de formulario o un componente con aspecto de campo de entrada.
Ejemplo
El ejemplo de arriba es este archivo, renderizado en vivo:
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { VoltInput, VoltLabel, VoltTextarea } from '@voltui/components';
@Component({
selector: 'app-input-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [VoltInput, VoltLabel, VoltTextarea],
template: `
<div class="mx-auto max-w-sm space-y-6">
<div class="space-y-2">
<volt-label htmlFor="email">Email</volt-label>
<volt-input id="email" type="email" autocomplete="email" placeholder="[email protected]" />
</div>
<div class="space-y-2">
<volt-label htmlFor="quantity">Quantity</volt-label>
<div class="flex items-center gap-2">
<volt-input id="quantity" size="sm" class="w-24 font-mono" [(value)]="quantity" />
<volt-input size="md" aria-label="Medium input" placeholder="md" />
<volt-input size="lg" aria-label="Large input" placeholder="lg" />
</div>
</div>
<div class="space-y-2">
<volt-label htmlFor="username">Username</volt-label>
<volt-input id="username" state="success" value="volt" />
<volt-input state="error" aria-label="Invalid username" value="v!" />
</div>
<div class="space-y-2">
<volt-label htmlFor="message">Message</volt-label>
<volt-textarea id="message" placeholder="Type your message here." [rows]="3" />
</div>
</div>
`,
})
export class InputExample {
readonly quantity = signal('12');
}
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-input
Value: —
Aún no hay eventos. Interactúa con la vista previa para verlos aquí.
HTML
<volt-input type="email" [(value)]="email" placeholder="[email protected]" />Formularios y accesibilidad
<volt-input>es un envoltorio de ancho completo alrededor de un único<input>nativo.id,classyaria-labelpertenecen al elemento nativo y se eliminan del host, así que<label for>y<volt-label htmlFor>llegan al control y ningún id se duplica.aria-describedbytambién se aplica al input nativo. Dentro de<volt-form-field>sus ids se añaden a la pista y al error, sin sustituirlos; fuera de un campo son la descripción del input (se escribe en el navegador, así que una página renderizada en el servidor la obtiene al hidratarse).- Sin
id, el input recibe uno generado, numerado por aplicación para que la página renderizada en el servidor y la hidratada coincidan. - Enlázalo con
[(value)],formControl/formControlNameongModel. Escribir notifica el valor; un valor que escribe tu código (setValue,reset, un cambio del modelo) no vuelve como cambio. - Se marca como tocado al perder el foco.
aria-invalid="true"aparece cuando el control es inválido y está tocado, o cuando ponesstate="error";statepor sí solo solo cambia el color. required,readonly,disabled,type,name,placeholderyautocompletese escriben en el input nativo. Un control deshabilitado desde Forms también queda deshabilitado.
aria-describedby requiere @voltui/components 1.4.1 o posterior. La última versión en npm cuando se generó esta página era la 1.3.3.Referencia de la API
| Entrada | Tipo | Por defecto |
|---|---|---|
| id | string | '' |
| type | string | 'text' |
| name | string | '' |
| placeholder | string | '' |
| autocomplete | string | '' |
| ariaLabel | string | '' |
| aria-label | string | undefined | undefined |
| aria-describedby | string | null | undefined | undefined |
| value | string | '' |
| size | InputVariants['size'] | 'md' |
| state | InputVariants['state'] | 'default' |
| class | string | '' |
| disabled | boolean | false |
| readonly | boolean | false |
| required | boolean | false |
| Salida | Tipo |
|---|---|
| valueChange | string |
Variantes CVA
| Propiedad | Opciones | Por defecto |
|---|---|---|
| size | sm | md | lg | md |
| state | default | error | success | default |
Instalación
Copia el código en tu proyecto:
npx @voltui/cli add input
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/input.
import {
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
forwardRef,
input,
model,
signal,
viewChild,
ElementRef,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NgpInput } from 'ng-primitives/input';
import { VoltAriaInvalid } from '../../aria-invalid';
import { injectFormControlState } from '../../form-control-state';
import { injectFormFieldState } from 'ng-primitives/form-field';
import {
forwardAttributesFromHost,
forwardClassFromHost,
forwardDescribedBy,
} from '../../host-forwarding';
import { injectVoltId } from '../../volt-ids';
import { inputVariants, type InputVariants } from './variants';
import { cn } from '../../utils';
const HOST_CLASSES = 'block w-full';
/**
* Text input bound with `[(value)]`, `formControl` or `ngModel`.
*
* The host is a full-width block wrapper. `class`, `id` and `aria-label` belong to the native
* `<input>`: they are applied there and removed from the host.
*/
@Component({
selector: 'volt-input',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgpInput, VoltAriaInvalid],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => VoltInput),
multi: true,
},
],
host: {
class: HOST_CLASSES,
},
template: `
<input
#control
ngpInput
[id]="controlId()"
[type]="type()"
[name]="name()"
[placeholder]="placeholder()"
[autocomplete]="autocomplete()"
[attr.aria-label]="ariaLabel() || ariaLabelAttribute() || null"
[readonly]="readonly()"
[required]="required()"
[disabled]="isDisabled()"
[value]="value()"
[attr.aria-invalid]="invalid() ? 'true' : null"
[voltAriaInvalid]="invalid()"
[attr.data-size]="size()"
[class]="classes()"
(input)="onInput($event)"
(blur)="onTouched()"
/>
`,
})
export class VoltInput implements ControlValueAccessor {
protected readonly formControlState = injectFormControlState();
readonly id = input('');
readonly type = input('text');
readonly name = input('');
readonly placeholder = input('');
readonly autocomplete = input('');
readonly ariaLabel = input('');
/** Same as `ariaLabel`, for the attribute spelling consumers write naturally. */
// eslint-disable-next-line @angular-eslint/no-input-rename -- `ariaLabel` (1.0) already owns the camelCase name
readonly ariaLabelAttribute = input<string | undefined>(undefined, { alias: 'aria-label' });
/**
* Ids of elements that describe the control, applied to the native element. Inside a
* `volt-form-field` they are added to the hint and error descriptions, not replacing them.
*/
readonly ariaDescribedby = input<string | null | undefined>(undefined, {
alias: 'aria-describedby',
});
private readonly control = viewChild.required<ElementRef<HTMLElement>>('control');
readonly value = model('');
readonly size = input<InputVariants['size']>('md');
/** Visual state. `error` also sets `aria-invalid`; an invalid touched form control implies it. */
readonly state = input<InputVariants['state']>('default');
/** Classes for the native `<input>`, merged over the defaults with `cn()`. */
readonly class = input<string>('');
readonly disabled = input<boolean, unknown>(false, { transform: booleanAttribute });
readonly readonly = input<boolean, unknown>(false, { transform: booleanAttribute });
readonly required = input<boolean, unknown>(false, { transform: booleanAttribute });
/** A generated id keeps `<volt-label>` / FormField associations working without one. */
private readonly generatedId = injectVoltId('volt-input');
protected readonly controlId = computed(() => this.id() || this.generatedId);
private readonly controlDisabled = signal(false);
protected readonly isDisabled = computed(() => this.disabled() || this.controlDisabled());
protected readonly classes = computed(() =>
cn(inputVariants({ size: this.size(), state: this.state() }), this.class())
);
private onChange: (value: string) => void = () => {};
protected onTouched: () => void = () => {};
constructor() {
forwardClassFromHost(HOST_CLASSES);
forwardAttributesFromHost('id', 'aria-label');
const formField = injectFormFieldState({ optional: true });
forwardDescribedBy(
this.ariaDescribedby,
() => this.control().nativeElement,
() => formField()
);
}
/** Not a `computed`: Forms' touched/invalid flags are not signals. */
protected invalid(): boolean {
return this.state() === 'error' || this.formControlState.invalid();
}
protected onInput(event: Event): void {
const nextValue = (event.target as HTMLInputElement).value;
this.value.set(nextValue);
this.onChange(nextValue);
}
writeValue(value: string | null | undefined): void {
this.value.set(value ?? '');
}
registerOnChange(fn: (value: string) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.controlDisabled.set(isDisabled);
}
}