Forms
Input & Forms
Displays a form input field or a component that looks like an input field.
Example
The example above is this file, rendered live:
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');
}
Playground
Change the inputs and interact with the preview: the events panel shows what the component emits, and the code follows your settings.
volt-input
Value: —
No events yet. Interact with the preview to see them here.
HTML
<volt-input type="email" [(value)]="email" placeholder="[email protected]" />Forms and accessibility
<volt-input>is a full-width wrapper around one native<input>.id,classandaria-labelbelong to the native element and are removed from the host, so<label for>and<volt-label htmlFor>reach the control and no id is duplicated.aria-describedbyis applied to the native input too. Inside<volt-form-field>its ids are added to the hint and error, not in place of them; outside a field they are the input's description (written in the browser, so a server-rendered page gains it on hydration).- Without an
id, the input gets a generated one, numbered per application so the server-rendered page and the hydrated page agree. - Bind it with
[(value)],formControl/formControlNameorngModel. Typing reports the value; a value written by your code (setValue,reset, a model change) does not echo back as a change. - It is marked touched when it loses focus.
aria-invalid="true"appears when the control is invalid and touched, or when you setstate="error";statealone only changes the color. required,readonly,disabled,type,name,placeholderandautocompleteare written to the native input. A control disabled through Forms is disabled too.
aria-describedby needs @voltui/components 1.4.1 or later. The latest version on npm when this page was built was 1.3.3.API Reference
| Input | Type | Default |
|---|---|---|
| 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 |
| Output | Type |
|---|---|
| valueChange | string |
CVA variants
| Prop | Options | Default |
|---|---|---|
| size | sm | md | lg | md |
| state | default | error | success | default |
Installation
Copy the source into your project:
npx @voltui/cli add input
Or import it from the package:
npm install @voltui/components
Source
Copy this code to your project. The component uses 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);
}
}