Input

The <smart-input> component renders a form input for a single model field by delegating to a sub-component chosen by FieldType. It selects a sub-component based on the FieldType resolved from @Field() decorator metadata via an internal baseMap and an optional extendMap injected via INPUT_FIELD_COMPONENTS_TOKEN. Shows error messages via <smart-input-error> when the control is touched and invalid.


Usage

<smart-input [options]="options" />

The preview renders the code above in an application that registers every preset (provideSmartPresets(), see Installation) and the English translations; without the presets, a component that has one renders its standard implementation instead, for most components unstyled markup.

Components

InputComponent (<smart-input>)

Main wrapper component. Resolves fieldOptions from @Field() decorator metadata on the model, then selects a sub-component from baseMap (or extendMap override) based on fieldOptions.type and renders it via NgComponentOutlet, forwarding options, fieldOptions and the class it receives. Also renders an inline info button when fieldOptions.info is set and a loader while control.status === 'PENDING'. Below the input, renders <smart-input-error> when control.errors are present and the control has been touched. A field whose options (for the current mode) set hide: true renders nothing.

InputBaseComponent (abstract)

Abstract base directive for all input sub-components. Provides:

  • options: InputSignal<InputOptions<T> | undefined> — field configuration (control, fieldKey, model, mode, treeLevel, possibilities, component)
  • fieldOptions: InputSignal<IFieldOptions | undefined> (a required input) — resolved field decorator metadata
  • cssClass: InputSignal<string> (alias class) — external CSS classes, forwarded by <smart-input>
  • internalOptions, control, required, possibilities — populated via effect when options change
  • afterSetOptionsHandler() — hook invoked after options resolve, used by sub-components for validator/possibilities setup
  • formControl, formControlArray, formControlGroup — typed accessors for control

InputPossibilitiesBaseComponent (abstract)

Extends InputBaseComponent for sub-components that need list possibilities: the radio and check components (standard and preset) and the enum preset. Its possibilities signal holds, in this order of precedence:

  1. the list in the signal MODEL_POSSIBILITIES_PROVIDER returns from get({ type, key, instance }) (the model's class, the field key and the parent form's value), while that signal's value is not null;
  2. else options.possibilities;
  3. else the possibilities of the field's @Field() metadata (read through the first item of an array model): an object map { text: id }, such as an enum, as a list for the radio components and the enum preset, a list as it is for the check components.

The provider is asked when the options are set and again 500 ms after the parent form's value last changed, so the list can depend on other fields; a provider signal filled later (after an HTTP call, for instance) updates the field, and after a new question the former list stays until the new signal holds one. The token is optional: without a provider the field shows the input options, else the field's own possibilities. The check components keep each possibility's checked in line with the control value (an id in the value, or equal to it) whenever the list or the value changes.

A subclass that overrides afterSetOptionsHandler() calls super.afterSetOptionsHandler() first. Two more protected hooks are there to override: afterPossibilitiesChange(), which runs whenever the list may have changed, and getModelPossibilities(), the fallback read from the field's metadata.

InputFileBaseComponent (abstract)

Extends InputBaseComponent for the uploading fields (attachment, image, pdf, video and the file and logo presets). It listens to the hidden #inputObj file input, checks the picked file against its accept list (a toast with INPUT.ERRORS.invalidFileType otherwise), uploads it through FileService and sets the result as the control value. It exposes loading, percent, file and the addButtonOptions, showButtonOptions and deleteButtonOptions of the buttons the fields render.

InputErrorComponent (<smart-input-error>)

The validation messages <smart-input> renders under a touched field. Its only input is errors (the control's ValidationErrors). Messages, in order: required (which hides confirm), confirm, invalidNip, invalidUnique, email, phoneNumber, pesel or invalidPesel (one message), minlength, maxlength, min, max and customMessage (shown as is), translated from INPUT.ERRORS.*. InputComponent always renders this component; there is no token to replace it.

Default Sub-Components

FieldTypeSub-componentSelectorDescription
textInputTextComponentsmart-input-textPlain text input
emailInputEmailComponentsmart-input-emailEmail input
passwordInputPasswordComponentsmart-input-passwordPassword input; adds <smart-password-strength> when the field's possibilities.strength is set
nipInputNipComponentsmart-input-nipNIP with built-in invalidNip validator
peselInputPeselComponentsmart-input-peselPESEL text input (the form factory adds the pesel check; the preset adds invalidPesel too)
intInputIntComponentsmart-input-intInteger input (type="number" step="1")
floatInputFloatComponentsmart-input-floatDecimal input (type="number" step="0.01")
currencyInputCurrencyComponentsmart-input-currencyCurrency input (type="number" step="0.01")
phoneNumberInputPhoneNumberComponentsmart-input-phone-numberTelephone input
phoneNumberPlInputPhoneNumberPlComponentsmart-input-phone-number-plTelephone input + built-in length(9) validator
longTextInputLongTextComponentsmart-input-long-textRich text editor (ngx-editor)
dateInputDateComponentsmart-input-dateHTML date input (type="date")
dateWithEditInputDateWithEditComponentsmart-input-date-with-editDigit-by-digit date via <smart-date-edit>
dateRangeInputDateRangeComponentsmart-input-date-rangeDate range via <smart-date-range>
flagInputFlagComponentsmart-input-flagSingle checkbox
radioInputRadioComponentsmart-input-radioRadio group (from possibilities)
checkInputCheckComponentsmart-input-checkCheckbox group (from possibilities)
enumInputEnumComponentsmart-input-enumOne checkbox per key of the field's enum; the value is the list of checked keys (the preset differs, see below)
colorInputColorComponentsmart-input-colorColor picker (ngx-color-picker)
logoInputLogoComponentsmart-input-logoImage picker with inline preview; stores a base64 data: URL, no upload (the preset differs, see below)
addressInputAddressComponentsmart-input-addressNested FormGroup (city/zip/street/building/flat)
objectInputObjectComponentsmart-input-objectNested form via FORM_COMPONENT_TOKEN
arrayInputArrayComponentsmart-input-arrayDynamic array of nested forms
intsInputIntsComponentsmart-input-intsDynamic list of integer inputs
stringsInputStringsComponentsmart-input-stringsDynamic list of string inputs
fileInputFileComponentsmart-input-fileGeneric file chooser; keeps the picked File as the value, no upload (the preset differs, see below)
attachmentInputAttachmentComponentsmart-input-attachmentFile upload (any type) with download/delete
imageInputImageComponentsmart-input-imageImage upload with preview
pdfInputPdfComponentsmart-input-pdfPDF upload with show/delete
videoInputVideoComponentsmart-input-videoVideo upload with play/delete

API

InputComponent Inputs

InputTypeDefaultDescription
optionsInputSignal<InputOptions<T> | undefined>undefinedField configuration
classInputSignal<string>''External CSS classes, forwarded to the field component (alias for cssClass)

InputOptions

InputOptions<T> is IInputOptions & IInputFromFieldOptions<T>.

FieldTypeDefaultDescription
treeLevelnumberrequiredNesting depth (0 at the top; nested object / array forms go one deeper).
controlUntypedFormControl | UntypedFormArrayrequiredThe control of the field.
possibilitiesWritableSignal<{ id: any; text: string; checked: boolean }[]>—The options of a radio, check or enum preset field: the MODEL_POSSIBILITIES_PROVIDER list wins over them, they win over the field's own possibilities. The standard enum (the enum's keys) and the other field types do not read it.
componentType<InputBaseComponent<any>>—A field component used instead of the one of the field type (wins over the token).
modelTrequiredThe model instance whose @Field() metadata is read.
fieldKeystringrequiredThe field's key; a <key>Confirm key reads the metadata of <key>.
mode'create' | 'update' | string—Merges the @Field({ create }) / @Field({ update }) overrides into the field options.

Notes:

  • fieldKey ending with Confirm is stripped — confirm variants share the original field's @Field() metadata.
  • mode === 'create' or 'update' merges the matching @Field({ create: … }) / @Field({ update: … }) override into the resolved fieldOptions.
  • If options.component is provided, it overrides everything (both baseMap and token).

INPUT_FIELD_COMPONENTS_TOKEN

InjectionToken<Partial<Record<FieldTypeDef, Type<InputBaseComponent<any>>>>> from @smartsoft001/angular — allows substituting a sub-component for any field type.

Maps are merged ({ ...baseMap, ...extendMap }), so only selected types need to be overridden.

Preline field presets

Each field type ships a Preline-styled preset (Input<Field>PresetComponent, selector smart-input-<field>-preset) alongside the default Tailwind-UI-styled field component. The presets live in <field>/preset/ and all translate the Preline look to smart:-prefixed vanilla Tailwind with explicit dark: variants. Apply them by providing the ready-made map INPUT_PRESET_FIELD_COMPONENTS for INPUT_FIELD_COMPONENTS_TOKEN (it covers all field types except the standalone validation-message preset), or with provideSmartPresets(), which provides it together with every other preset.

INPUT_PRESET_FIELD_COMPONENTS maps every FieldType that ships an input component (dateTime has no input component, so it has no map entry). The field-type presets and their selectors mirror the default components in the table above (smart-input-<field>-preset), including the most recently added ones:

FieldTypePreset componentSelectorLook
colorInputColorPresetComponentsmart-input-color-presetNative color input in a rounded frame + swatch + hex
objectInputObjectPresetComponentsmart-input-object-presetStyled card frame around the nested form (unchanged nesting)
addressInputAddressPresetComponentsmart-input-address-presetResponsive grid of Preline text sub-inputs (street/no/zip/city)
flagInputFlagPresetComponentsmart-input-flag-presetPreline checkbox (blue checked state) + inline label
pdfInputPdfPresetComponentsmart-input-pdf-presetDashed drop-zone (accept .pdf) + show/delete preview
videoInputVideoPresetComponentsmart-input-video-presetDashed drop-zone (accept .mp4) + play/delete + <video>
arrayInputArrayPresetComponentsmart-input-array-presetItem cards (space-y-2), outline add / ghost-red remove

Where a preset behaves differently from the standard component of its type:

FieldTypeStandardPreset
enumCheckboxes of the enum's keys; value: list of keysA <select> of the possibilities (the provider's, else options.possibilities, else the field's); value: one possibility id
fileKeeps the picked File as the value (no upload)Uploads through FileService (InputFileBaseComponent); value: the API result
logoStores a base64 data: URL (no upload)Uploads like image (.jpg,.png,.jpeg)
peselNo validator of its ownAdds an invalidPesel check (shown with the same message as pesel)

Notes:

  • Interactive Preline widgets (enum select, password strength meter, date pickers, file drop-zone) are driven by Angular signals — the Preline JS plugins are not required.
  • File-based presets (pdf, video, plus file/image/attachment) keep the hidden #inputObj file input and reuse InputFileBaseComponent's upload/button wiring; the drop-zone and drag-and-drop are added on top.
  • object reuses FORM_COMPONENT_TOKEN and the NgComponentOutlet/DynamicIoDirective nesting of the default component — only the surrounding frame is styled, the nested rendering is untouched.
  • array extends the concrete InputArrayComponent (add/remove/CVA logic untouched); each item is a card, the empty state renders an em dash, and both add and remove buttons hide when fieldOptions().possibilities.static is true.
  • InputErrorPresetComponent (smart-input-error-preset) is a Preline-styled validation-message variant. Because InputComponent hard-codes <smart-input-error> (no token for it), use this preset via its selector directly — it is not part of INPUT_PRESET_FIELD_COMPONENTS, and wiring it into the wrapper is out of scope.

Extending the base class

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  ViewEncapsulation,
} from '@angular/core';
import {
  ReactiveFormsModule,
  UntypedFormControl,
  Validators,
} from '@angular/forms';

import {
  INPUT_FIELD_COMPONENTS_TOKEN,
  InputBaseComponent,
  InputComponent,
  InputOptions,
  ModelLabelPipe,
} from '@smartsoft001/angular';
import { Field, FieldType, Model } from '@smartsoft001/models';

@Model({ titleKey: 'nickname' })
export class DocsProfile {
  @Field({ type: FieldType.text })
  nickname = '';
}

@Component({
  selector: 'docs-custom-input-text',
  template: `
    @if (control) {
      <label class="docs-input__label">
        {{
          control?.parent?.value
            | smartModelLabel
              : internalOptions.fieldKey
              : internalOptions?.model?.constructor
        }}
        @if (required) {
          <span class="docs-input__required">*</span>
        }
      </label>
      <input
        type="text"
        [class]="fieldClasses()"
        [formControl]="formControl"
        [attr.autofocus]="fieldOptions()?.focused ? true : null"
      />
    }
  `,
  imports: [ReactiveFormsModule, ModelLabelPipe],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomInputTextComponent<T> extends InputBaseComponent<T> {
  // The class passed to `<smart-input>` arrives in the inherited `cssClass`
  // input (alias `class`).
  fieldClasses = computed(() => {
    const classes = ['docs-input__field'];
    const extra = this.cssClass();
    if (extra) classes.push(extra);
    return classes.join(' ');
  });

  // `control`, `formControl`, `required`, `internalOptions` and
  // `fieldOptions()` are all set up by InputBaseComponent from the options
  // that `<smart-input>` forwards.
}

@Component({
  selector: 'docs-input-custom-example',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputComponent],
  // Inputs are swapped per field type: every FieldType.text field below this
  // component now renders CustomInputTextComponent instead of the built-in
  // one. A single field can also be overridden with `options.component`.
  providers: [
    {
      provide: INPUT_FIELD_COMPONENTS_TOKEN,
      useValue: { [FieldType.text]: CustomInputTextComponent },
    },
  ],
  template: `<smart-input [options]="options" />`,
})
export class InputCustomExampleComponent {
  control = new UntypedFormControl('', Validators.required);

  // `<smart-input>` reads the @Field metadata of `model[fieldKey]` to decide
  // which field component to render, so the model drives the dispatch.
  options: InputOptions<DocsProfile> = {
    control: this.control,
    fieldKey: 'nickname',
    model: new DocsProfile(),
    treeLevel: 0,
  };
}

Source

The component lives in packages/shared/angular/src/lib/components/input and is documented for Claude Code by the angular-components-input skill.

SmartInput renders one field of a model-driven form: it reads the field's @Field options for the form's mode, picks the field component of the field's FieldType (or options.component), and renders it with the field's info tooltip, a loader while an async validator runs, and the validation messages once the control is touched. SmartForm renders one SmartInput per control, so most applications use it indirectly; render it yourself when you lay out a form's fields by hand. Field components are resolved from inputFieldComponents on SmartProvider over the library's defaults (INPUT_PRESET_FIELD_COMPONENTS gives the styled set), and the messages render through components['input-error'].


Usage

import { useState } from 'react';

import { Field, FieldType, Model } from '@smartsoft001/models';
import {
  InputOptions,
  SmartFormControl,
  SmartInput,
  SmartValidators,
} from '@smartsoft001/react';

@Model({})
class Newsletter {
  @Field({ type: FieldType.email, required: true })
  email = '';
}

export function InputUsageExample() {
  // Created once, so the control keeps its value across renders.
  const [control] = useState(
    () =>
      new SmartFormControl('', [
        SmartValidators.required,
        SmartValidators.email,
      ]),
  );
  const [model] = useState(() => new Newsletter());

  // SmartInput reads the @Field metadata of `model[fieldKey]` and renders the
  // matching field component (here: an email input).
  const options: InputOptions<Newsletter> = {
    control,
    model,
    fieldKey: 'email',
    mode: 'create',
    treeLevel: 0,
  };

  return <SmartInput options={options} />;
}

The preview renders the code above in an application that registers every preset (SMART_PRESET_COMPONENTS on SmartProvider, see Installation) and the English translations; without the presets, a component that has one renders its standard implementation instead, for most components unstyled markup.

Exports

All from @smartsoft001/react.

ExportKindWhat it is
SmartInputcomponentRenders the field component of the control's field type (or options.component), with the field's info tooltip, a loader while an async validator runs, and the validation messages once the control is touched.
SmartInputErrorcomponentThe messages of a field's validation errors.
SmartInputErrorPresetcomponentStyled validation messages (preset), each with an alert icon and role="alert".
SmartRichTextEditorcomponentA dependency-free rich-text editor: a menu bar over a contentEditable element whose HTML is the value.
useInputFilehookThe upload behaviour of the file fields: picking a file checks it against the input's accept list, uploads it through the file service with progress, and sets the attachment the API returns as the value.
useInputPossibilitieshookThe options of a field with possibilities: the ones the model possibilities provider returns, asked again 500 ms after the form's value last changed so they can depend on other fields, or else the ones in the input options.
useInputhookWhat every field component shares: the control and its live state, whether it is required, the translated label and the handlers that bind an element to the control (a change sets the value and marks the control dirty, a blur marks it touched).
getDefaultInputFieldComponentsfunctionThe standard field component of every FieldType (the map SmartInput falls back to).
getInputErrorMessagesfunctionThe messages a field shows for its validation errors, in a fixed order.
resolveInputFieldOptionsfunctionThe options of the field an input renders, merged with the options of the form's mode: a <key>Confirm control takes the options of <key>, and an array model is read through its first item.
INPUT_PRESET_FIELD_COMPONENTSconstThe Preline-styled field presets, by FieldType.
LONG_TEXT_TOOLBARconstThe full menu of SmartRichTextEditor (its default toolbar), typed SmartRichTextToolbar.

Every field component of the table under "Field types" is exported too (SmartInputText, SmartInputTextPreset, ...), with the hooks their standard and preset variants share. Use them in a custom field component of the same type.

Hook / functionWhat it is
useInputAddressPartBinds the input of one part of an address group to its control (value, dirty on change, touched on blur, disabled with the part) and gives an id for its label.
useInputArrayThe array field: the item forms, add(), remove(index), move(from, to), getItemDragProps(index) and isStatic (possibilities.static).
useInputCheckThe check field: the possibilities (provider, input options, else the model field's), kept checked in line with the value, and toggle(item).
syncInputCheckPossibilitiesThe possibilities with checked set from a value (what useInputCheck uses).
useInputColorThe color field: the shown colour, picking and clearing (null).
useInputImageuseInput and useInputFile plus the preview URL of the image field and the logo preset.
useInputIntsThe ints field: one row per number plus a trailing row to add one.
useInputNipuseInput plus the invalidNip validator added to the control.
useInputObjectThe object field: the options of the nested form, one tree level deeper.
useInputPasswordThe password field: the strength rating and the passwordStrength validator it drives.
useInputPhoneNumberPluseInput plus the minLength(9) / maxLength(9) validators.
useInputRadioThe radio field: the possibilities (provider, input options, else the model field's object map).
getModelFieldPossibilitiesListThe model field's possibilities object map as a list (the fallback of the radio and enum preset fields).
useInputVideouseInput and useInputFile plus the player of the video fields.
useInputFileDropZoneThe drop zone of the pdf, video and attachment presets (click / Enter / Space opens the picker, a drop uploads like a picked file); options UseInputFileDropZoneOptions.
toNumberValueThe value of a number <input>: empty is null, else parseFloat.

The preset's class helpers (getInputEmailPresetClasses, getInputEmailPresetLabelClasses, getInputNipPresetClasses, getInputNipPresetLabelClasses, getInputPhoneNumberPlPresetClasses, getInputPhoneNumberPlPresetLabelClasses, getInputPhoneNumberPlPresetWrapperClasses, getInputPhoneNumberPlPresetPrefixClasses, getInputPhoneNumberPresetClasses, getInputPhoneNumberPresetLabelClasses, getInputTextPresetClasses, getInputTextPresetLabelClasses) are exported too, for a custom implementation that wants the preset look.

Props and Types

SmartInputProps<T = any>

The props of <SmartInput>.

PropTypeDefaultDescription
options?InputOptions<T>—The field to render: control, model, field key, mode, tree level, possibilities, component.
className?string—Passed to the field component (usually appended to its input).

SmartInputErrorProps

PropTypeDefaultDescription
errors?SmartValidationErrors | null—The control's errors.

SmartInputFieldProps<T = any>

The props every field component receives from <SmartInput>: the input options (control, model, field key, mode, tree level, possibilities) and the field's options for the current mode.

PropTypeDefaultDescription
options?InputOptions<T>—The input options SmartInput received.
fieldOptions?IFieldOptions—The field's @Field options merged with the options of the mode.
className?string—The className of SmartInput.

SmartRichTextEditorProps

Props of the rich-text editor of longText fields.

PropTypeDefaultDescription
value?string | null—The HTML to edit; rendered sanitised when it does not come from here.
placeholder?string—Placeholder of the empty editor.
disabled?booleanfalseMakes the editor read-only.
toolbar?SmartRichTextToolbarLONG_TEXT_TOOLBARThe menu groups; the full menu (formatting, lists, headings, link, image, colours, alignment) by default.
labelledBy?string—The id of the element labelling the editor.
onChange?(html: string) => void—Called with the HTML of the content after every change.
onBlur?() => void—Called when the editor loses the focus.

SmartRichTextToolbar is SmartRichTextToolbarItem[][], one array per group of the menu. An item is a SmartRichTextToggle ('bold', 'italic', 'underline', 'strike', 'code', 'blockquote', 'ordered_list', 'bullet_list', 'align_left', 'align_center', 'align_right', 'align_justify'), a SmartRichTextColorKind ('text_color', 'background_color'), 'link', 'image' or { heading: SmartRichTextHeading[] } ('h1' to 'h6'). All these types are exported.

IInputOptions

FieldTypeDefaultDescription
treeLevelnumberrequiredNesting depth (0 at the top; nested object / array forms go one deeper).
controlSmartAbstractControlrequiredThe control of the field (form.controls[fieldKey]).
possibilities?SmartPossibility[]—The options of a radio, check or preset enum field: the model possibilities provider's win over them, they win over the field's own possibilities. The standard enum (the enum's keys) and the other types do not read them.
component?InputComponentType<any>the component of the field's typeA field component used instead of the type's one.

IInputFromFieldOptions<T>

FieldTypeDefaultDescription
modelTrequiredThe model instance the form was built from (its @Field metadata is read).
fieldKeystringrequiredThe field's key (a <key>Confirm key reads the options of <key>).
mode?'create' | 'update' | string—The form mode whose options are merged (create, update, ...).
  • InputOptions<T>: IInputOptions & IInputFromFieldOptions<T> — What SmartInput takes: IInputOptions & IInputFromFieldOptions<T>.

SmartPossibility, SmartAbstractControl are described in the react-forms and react-provider skills.

Field types

SmartInput picks the component by fieldOptions.type (from @smartsoft001/models' FieldType). The standard component is the default; the preset one is what INPUT_PRESET_FIELD_COMPONENTS registers. Where the two behave differently, it is noted.

FieldTypeStandardPresetNotes
textSmartInputTextSmartInputTextPresetText input.
longTextSmartInputLongTextSmartInputLongTextPresetRich-text editor (SmartRichTextEditor); the value is HTML, shown sanitised.
emailSmartInputEmailSmartInputEmailPresettype="email"; the form factory adds the email check.
passwordSmartInputPasswordSmartInputPasswordPresetWith possibilities: { strength: true } a strength meter sets the passwordStrength error until the password is strong. confirm: true adds a <key>Confirm field.
int / float / currencySmartInputInt / SmartInputFloat / SmartInputCurrency…PresetNumber inputs (step 1 / 0.01 / 0.01); empty sets null.
intsSmartInputIntsSmartInputIntsPresetA list of numbers, one row each plus a row to add.
stringsSmartInputStringsSmartInputStringsPresetA list of strings (the preset as chips).
flagSmartInputFlagSmartInputFlagPresetCheckbox bound to a boolean.
radioSmartInputRadioSmartInputRadioPresetOne radio per possibility; the value is its id.
checkSmartInputCheckSmartInputCheckPresetOne checkbox per possibility; the value is the list of checked ids.
enumSmartInputEnumSmartInputEnumPresetDiffers: the standard renders checkboxes of the enum's keys (value: list of keys); the preset renders a <select> (value: one possibility id).
dateSmartInputDateSmartInputDatePresetNative type="date", YYYY-MM-DD.
dateWithEditSmartInputDateWithEditSmartInputDateWithEditPresetSmartDateEdit (digit inputs) bound to the control.
dateRangeSmartInputDateRangeSmartInputDateRangePresetIDateRange value; the standard uses SmartDateRange, the preset two native date inputs.
nipSmartInputNipSmartInputNipPresetAdds the NIP check (invalidNip) to the control.
peselSmartInputPeselSmartInputPeselPresetThe form factory adds the pesel check; differs: the preset adds its own invalidPesel check to the control too (same message).
phoneNumberSmartInputPhoneNumberSmartInputPhoneNumberPresettype="tel"; the form factory adds the phoneNumber check.
phoneNumberPlSmartInputPhoneNumberPlSmartInputPhoneNumberPlPresetExactly 9 characters (minlength / maxlength); the preset shows a +48 addon.
colorSmartInputColorSmartInputColorPresetNative colour picker with a clear button.
fileSmartInputFileSmartInputFilePresetDiffers: the standard keeps the picked File as the value (no upload); the preset uploads it through the file service.
attachment / pdf / videoSmartInputAttachment / SmartInputPdf / SmartInputVideo…Preset (drop zones)Upload through the file service; the value is the attachment the API returns.
imageSmartInputImageSmartInputImagePreset.jpg,.png,.jpeg upload with a preview.
logoSmartInputLogoSmartInputLogoPresetDiffers: the standard stores a base64 data: URL (no upload); the preset uploads like image.
objectSmartInputObjectSmartInputObjectPresetA nested SmartForm for the field's group (classType model), one tree level deeper.
arraySmartInputArraySmartInputArrayPresetA nested SmartForm per item, an add button and drag-and-drop reordering (remove button in the preset only; possibilities.static disables changes).
addressSmartInputAddressSmartInputAddressPresetA labelled input per part (city, zip code, street, building and flat number).

dateTime has no input component: a dateTime field renders nothing unless you register one under inputFieldComponents[FieldType.dateTime] or pass component.

Uploading fields need a file service: give SmartProvider a fileServiceConfig ({ apiUrl }) or a fileService; without one, a picked file is not uploaded. Files go to <apiUrl>/attachments.

Possibilities

The radio and check fields (standard and preset) and the preset enum list their possibilities from, in this order of precedence:

  1. the model possibilities provider (modelPossibilitiesProvider on SmartProvider), asked with { type, key, instance } (the model's class, the field key and the form's value) when the field mounts and again 500 ms after the form's value last changed, as long as it returns a list or a promise of one (a null or undefined result is ignored);
  2. else options.possibilities;
  3. else the field's own possibilities (read through the first item of an array model): an object map { text: id }, such as an enum, as a list for radio and the preset enum, a list as it is for check.

The check fields check each possibility whose id is in the value (or equals it). The standard enum lists the keys of the enum in fieldOptions.possibilities and asks no provider. useInputPossibilities returns the first two sources (the provider's, else the input options'), so a custom field adds its own fallback.

Labels, info and messages

  • The label is the label provider's (modelLabelProvider on SmartProvider) or the translation of MODEL.<key> (see react-provider).
  • A field with info: '...' shows a SmartInfo tooltip; a field with hide: true (for the mode) renders nothing.
  • Messages are shown once the control is touched, from its errors, in a fixed order: required (which hides confirm), confirm, invalidNip, invalidUnique, email, phoneNumber, pesel or invalidPesel (one message), minlength, maxlength, min, max, and customMessage (its value is shown as is). The texts come from INPUT.ERRORS.* translations. getInputErrorMessages(errors, t) returns that list for a custom message component.

Choosing the component of a field

  1. options.component on SmartInput (SmartForm fills it from IFormOptions.inputComponents[fieldKey], and CRUD screens from CrudFullConfig.inputComponents);
  2. else inputFieldComponents[type] registered on SmartProvider;
  3. else the library's standard component for the type (getDefaultInputFieldComponents()).

Replacing the Implementation

  • Per field type, application-wide: inputFieldComponents on SmartProvider maps a FieldType to a component taking SmartInputFieldProps. Spread the preset map to override only some types: { ...INPUT_PRESET_FIELD_COMPONENTS, [FieldType.text]: MyText }.
  • Per field of one form: IFormOptions.inputComponents ({ [fieldKey]: Component }), or options.component when you render SmartInput yourself.
  • Validation messages: the input-error registry key (components={{ 'input-error': SmartInputErrorPreset }}); the component receives { errors }.
  • SMART_PRESET_COMPONENTS registers the preset field map and SmartInputErrorPreset together with the other presets.

Hooks

useInputFile

The upload behaviour of the file fields: picking a file checks it against the input's accept list, uploads it through the file service with progress, and sets the attachment the API returns as the value. Also the options of the add, show and delete buttons the file fields render.

ReturnsTypeDescription
inputRefRefObject<HTMLInputElement | null>Attach to the hidden file input.
loadingbooleantrue while a file uploads.
percentnumber | undefinedUpload progress (0–100), undefined when unknown.
fileFile | nullThe picked File.
onFileChange(event: ChangeEvent<HTMLInputElement>) => voidThe input's change handler: checks accept, uploads through the file service and sets the returned attachment as the value.
addButtonOptionsIButtonOptionsIButtonOptions of the add / change button (opens the picker).
showButtonOptionsIButtonOptionsIButtonOptions of the download / show button.
deleteButtonOptionsIButtonOptionsIButtonOptions of the delete button.

useInputPossibilities

The options of a field with possibilities: the ones the model possibilities provider returns, asked again 500 ms after the form's value last changed so they can depend on other fields, or else the ones in the input options. null when there are none; the field then falls back to its model's possibilities.

useInput

What every field component shares: the control and its live state, whether it is required, the translated label and the handlers that bind an element to the control (a change sets the value and marks the control dirty, a blur marks it touched).

ReturnsTypeDescription
controlSmartAbstractControl<any> | nullThe field's control (options.control).
stateSmartControlState<any> | nullThe control's live state (useControlState).
valueanyThe control's value.
requiredbooleanWhether the control reports required for an empty value (show a required mark).
disabledbooleanWhether the control is disabled.
labelstringThe field label: the label provider's, or MODEL.<key> translated.
fieldKeystringoptions.fieldKey.
modelT | undefinedoptions.model.
modestring | undefinedoptions.mode.
treeLevelnumberoptions.treeLevel (0 by default).
fieldOptionsIFieldOptions | undefinedThe merged field options.
setValue(value: unknown) => voidSets the value as the user would: the control becomes dirty.
markAsTouched() => void | undefinedMarks the control as touched, as leaving the field does.
autoFocusbooleanAutofocus as fieldOptions.focused asks.

A custom field component takes SmartInputFieldProps and binds an element to the control through useInput:

import { useId, useState } from 'react';

import { Field, FieldType, Model } from '@smartsoft001/models';
import {
  cn,
  InputOptions,
  SmartFormControl,
  SmartInput,
  SmartInputFieldProps,
  SmartProvider,
  SmartValidators,
  useInput,
} from '@smartsoft001/react';

@Model({ titleKey: 'nickname' })
export class DocsProfile {
  @Field({ type: FieldType.text })
  nickname = '';
}

export function CustomInput<T>(props: SmartInputFieldProps<T>) {
  // useInput gives the control's live state, the translated model label,
  // whether the field is required and the handlers that bind the element.
  const {
    control,
    value,
    label,
    required,
    disabled,
    autoFocus,
    setValue,
    markAsTouched,
  } = useInput(props);
  const id = useId();

  if (!control) return null;

  return (
    <>
      <label htmlFor={id} className="docs-input__label">
        {label}
        {required && <span className="docs-input__required">*</span>}
      </label>
      <input
        id={id}
        type="text"
        className={cn('docs-input__field', props.className)}
        value={value ?? ''}
        disabled={disabled}
        autoFocus={autoFocus}
        onChange={(event) => setValue(event.target.value)}
        onBlur={markAsTouched}
      />
    </>
  );
}

// Inputs are swapped per field type: every FieldType.text field below the
// provider renders CustomInput. A module constant, so the context is stable.
const inputFieldComponents = { [FieldType.text]: CustomInput };

export function InputCustomExample() {
  const [control] = useState(
    () => new SmartFormControl('', SmartValidators.required),
  );
  const [model] = useState(() => new DocsProfile());

  // SmartInput reads the @Field metadata of `model[fieldKey]` to pick the
  // field component, so the model drives the dispatch.
  const options: InputOptions<DocsProfile> = {
    control,
    fieldKey: 'nickname',
    model,
    treeLevel: 0,
  };

  return (
    <SmartProvider inputFieldComponents={inputFieldComponents}>
      <SmartInput options={options} />
    </SmartProvider>
  );
}

useInputPossibilities gives a custom radio / check / enum component the options from the possibilities provider or the input options, and useInputFile the upload logic of the file fields.

Styling

  • Standard field components are lightly styled Tailwind inputs with smart:dark: variants; the preset set is the Preline look. className reaches the field component (usually its input).

Source

The component lives in packages/shared/react/src/lib/components/input and is documented for Claude Code by the react-components-input skill.