Документація/Input і форми
LanguageУкраїнська

Форми

Input і форми

Показує поле форми або компонент, що виглядає як поле вводу.

Приклад

Приклад вище — це цей файл, відрендерений наживо:

input-example.ts
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');
}

View source

Пісочниця

Змінюйте вхідні параметри та взаємодійте з попереднім переглядом: панель подій показує, що випромінює компонент, а код відповідає вашим налаштуванням.

volt-input

Value: —

Вхідні параметри

Події

Подій ще немає. Взаємодійте з попереднім переглядом, щоб побачити їх тут.

HTML

<volt-input type="email" [(value)]="email" placeholder="[email protected]" />

volt-input — розгорнутий попередній перегляд

Форми та доступність

  • <volt-input> — це обгортка на всю ширину навколо одного нативного <input>. id, class і aria-label належать нативному елементу й прибираються з хоста, тож <label for> і <volt-label htmlFor> вказують на сам елемент керування, і жоден id не дублюється.
  • aria-describedby теж застосовується до нативного input. Усередині <volt-form-field> його id додаються до підказки й помилки, а не замінюють їх; поза полем вони стають описом input (атрибут записується в браузері, тож сторінка, відрендерена на сервері, отримує його під час гідратації).
  • Без id поле отримує згенерований, пронумерований у межах застосунку, тож сторінка, відрендерена на сервері, і гідратована сторінка збігаються.
  • Прив’язуйте його через [(value)], formControl / formControlName або ngModel. Введення тексту повідомляє значення; значення, яке записує ваш код (setValue, reset, зміна моделі), не повертається як зміна.
  • Поле позначається торкнутим, коли втрачає фокус. aria-invalid="true" з’являється, коли елемент керування невалідний і торкнутий, або коли ви задаєте state="error"; сам state змінює лише колір.
  • required, readonly, disabled, type, name, placeholder і autocomplete записуються в нативне поле. Елемент керування, вимкнений через Forms, теж вимикається.
Ще не опубліковано в npm: для aria-describedby потрібен @voltui/components 1.4.1 або новіший. Остання версія в npm на момент збирання цієї сторінки — 1.3.3.

Довідник API

ВхідТипЗа замовчуванням
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
ВихідТип
valueChangestring

Варіанти CVA

ВластивістьЗначенняЗа замовчуванням
size sm | md | lg md
state default | error | success default

Встановлення

Скопіюйте вихідний код у свій проєкт:

npx @voltui/cli add input

Або імпортуйте його з пакета:

npm install @voltui/components

Вихідний код

Скопіюйте цей код у свій проєкт. Компонент використовує ng-primitives/input.

input.ts
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);
  }
}

View source