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 metadatacssClass: InputSignal<string>(aliasclass) — external CSS classes, forwarded by<smart-input>internalOptions,control,required,possibilities— populated viaeffectwhen options changeafterSetOptionsHandler()— hook invoked after options resolve, used by sub-components for validator/possibilities setupformControl,formControlArray,formControlGroup— typed accessors forcontrol
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:
- the list in the signal
MODEL_POSSIBILITIES_PROVIDERreturns fromget({ type, key, instance })(the model's class, the field key and the parent form's value), while that signal's value is notnull; - else
options.possibilities; - else the
possibilitiesof 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
| FieldType | Sub-component | Selector | Description |
|---|---|---|---|
text | InputTextComponent | smart-input-text | Plain text input |
email | InputEmailComponent | smart-input-email | Email input |
password | InputPasswordComponent | smart-input-password | Password input; adds <smart-password-strength> when the field's possibilities.strength is set |
nip | InputNipComponent | smart-input-nip | NIP with built-in invalidNip validator |
pesel | InputPeselComponent | smart-input-pesel | PESEL text input (the form factory adds the pesel check; the preset adds invalidPesel too) |
int | InputIntComponent | smart-input-int | Integer input (type="number" step="1") |
float | InputFloatComponent | smart-input-float | Decimal input (type="number" step="0.01") |
currency | InputCurrencyComponent | smart-input-currency | Currency input (type="number" step="0.01") |
phoneNumber | InputPhoneNumberComponent | smart-input-phone-number | Telephone input |
phoneNumberPl | InputPhoneNumberPlComponent | smart-input-phone-number-pl | Telephone input + built-in length(9) validator |
longText | InputLongTextComponent | smart-input-long-text | Rich text editor (ngx-editor) |
date | InputDateComponent | smart-input-date | HTML date input (type="date") |
dateWithEdit | InputDateWithEditComponent | smart-input-date-with-edit | Digit-by-digit date via <smart-date-edit> |
dateRange | InputDateRangeComponent | smart-input-date-range | Date range via <smart-date-range> |
flag | InputFlagComponent | smart-input-flag | Single checkbox |
radio | InputRadioComponent | smart-input-radio | Radio group (from possibilities) |
check | InputCheckComponent | smart-input-check | Checkbox group (from possibilities) |
enum | InputEnumComponent | smart-input-enum | One checkbox per key of the field's enum; the value is the list of checked keys (the preset differs, see below) |
color | InputColorComponent | smart-input-color | Color picker (ngx-color-picker) |
logo | InputLogoComponent | smart-input-logo | Image picker with inline preview; stores a base64 data: URL, no upload (the preset differs, see below) |
address | InputAddressComponent | smart-input-address | Nested FormGroup (city/zip/street/building/flat) |
object | InputObjectComponent | smart-input-object | Nested form via FORM_COMPONENT_TOKEN |
array | InputArrayComponent | smart-input-array | Dynamic array of nested forms |
ints | InputIntsComponent | smart-input-ints | Dynamic list of integer inputs |
strings | InputStringsComponent | smart-input-strings | Dynamic list of string inputs |
file | InputFileComponent | smart-input-file | Generic file chooser; keeps the picked File as the value, no upload (the preset differs, see below) |
attachment | InputAttachmentComponent | smart-input-attachment | File upload (any type) with download/delete |
image | InputImageComponent | smart-input-image | Image upload with preview |
pdf | InputPdfComponent | smart-input-pdf | PDF upload with show/delete |
video | InputVideoComponent | smart-input-video | Video upload with play/delete |
API
InputComponent Inputs
| Input | Type | Default | Description |
|---|---|---|---|
options | InputSignal<InputOptions<T> | undefined> | undefined | Field configuration |
class | InputSignal<string> | '' | External CSS classes, forwarded to the field component (alias for cssClass) |
InputOptions
InputOptions<T> is IInputOptions & IInputFromFieldOptions<T>.
| Field | Type | Default | Description |
|---|---|---|---|
treeLevel | number | required | Nesting depth (0 at the top; nested object / array forms go one deeper). |
control | UntypedFormControl | UntypedFormArray | required | The control of the field. |
possibilities | WritableSignal<{ 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. |
component | Type<InputBaseComponent<any>> | — | A field component used instead of the one of the field type (wins over the token). |
model | T | required | The model instance whose @Field() metadata is read. |
fieldKey | string | required | The 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:
fieldKeyending withConfirmis stripped — confirm variants share the original field's@Field()metadata.mode==='create'or'update'merges the matching@Field({ create: … })/@Field({ update: … })override into the resolvedfieldOptions.- If
options.componentis provided, it overrides everything (bothbaseMapand 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:
| FieldType | Preset component | Selector | Look |
|---|---|---|---|
color | InputColorPresetComponent | smart-input-color-preset | Native color input in a rounded frame + swatch + hex |
object | InputObjectPresetComponent | smart-input-object-preset | Styled card frame around the nested form (unchanged nesting) |
address | InputAddressPresetComponent | smart-input-address-preset | Responsive grid of Preline text sub-inputs (street/no/zip/city) |
flag | InputFlagPresetComponent | smart-input-flag-preset | Preline checkbox (blue checked state) + inline label |
pdf | InputPdfPresetComponent | smart-input-pdf-preset | Dashed drop-zone (accept .pdf) + show/delete preview |
video | InputVideoPresetComponent | smart-input-video-preset | Dashed drop-zone (accept .mp4) + play/delete + <video> |
array | InputArrayPresetComponent | smart-input-array-preset | Item cards (space-y-2), outline add / ghost-red remove |
Where a preset behaves differently from the standard component of its type:
| FieldType | Standard | Preset |
|---|---|---|
enum | Checkboxes of the enum's keys; value: list of keys | A <select> of the possibilities (the provider's, else options.possibilities, else the field's); value: one possibility id |
file | Keeps the picked File as the value (no upload) | Uploads through FileService (InputFileBaseComponent); value: the API result |
logo | Stores a base64 data: URL (no upload) | Uploads like image (.jpg,.png,.jpeg) |
pesel | No validator of its own | Adds 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, plusfile/image/attachment) keep the hidden#inputObjfile input and reuseInputFileBaseComponent's upload/button wiring; the drop-zone and drag-and-drop are added on top. objectreusesFORM_COMPONENT_TOKENand theNgComponentOutlet/DynamicIoDirectivenesting of the default component — only the surrounding frame is styled, the nested rendering is untouched.arrayextends the concreteInputArrayComponent(add/remove/CVA logic untouched); each item is a card, the empty state renders an em dash, and both add and remove buttons hide whenfieldOptions().possibilities.staticis true.InputErrorPresetComponent(smart-input-error-preset) is a Preline-styled validation-message variant. BecauseInputComponenthard-codes<smart-input-error>(no token for it), use this preset via its selector directly — it is not part ofINPUT_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.
| Export | Kind | What it is |
|---|---|---|
SmartInput | component | Renders 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. |
SmartInputError | component | The messages of a field's validation errors. |
SmartInputErrorPreset | component | Styled validation messages (preset), each with an alert icon and role="alert". |
SmartRichTextEditor | component | A dependency-free rich-text editor: a menu bar over a contentEditable element whose HTML is the value. |
useInputFile | hook | 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. |
useInputPossibilities | hook | 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. |
useInput | hook | 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). |
getDefaultInputFieldComponents | function | The standard field component of every FieldType (the map SmartInput falls back to). |
getInputErrorMessages | function | The messages a field shows for its validation errors, in a fixed order. |
resolveInputFieldOptions | function | The 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_COMPONENTS | const | The Preline-styled field presets, by FieldType. |
LONG_TEXT_TOOLBAR | const | The 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 / function | What it is |
|---|---|
useInputAddressPart | Binds 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. |
useInputArray | The array field: the item forms, add(), remove(index), move(from, to), getItemDragProps(index) and isStatic (possibilities.static). |
useInputCheck | The check field: the possibilities (provider, input options, else the model field's), kept checked in line with the value, and toggle(item). |
syncInputCheckPossibilities | The possibilities with checked set from a value (what useInputCheck uses). |
useInputColor | The color field: the shown colour, picking and clearing (null). |
useInputImage | useInput and useInputFile plus the preview URL of the image field and the logo preset. |
useInputInts | The ints field: one row per number plus a trailing row to add one. |
useInputNip | useInput plus the invalidNip validator added to the control. |
useInputObject | The object field: the options of the nested form, one tree level deeper. |
useInputPassword | The password field: the strength rating and the passwordStrength validator it drives. |
useInputPhoneNumberPl | useInput plus the minLength(9) / maxLength(9) validators. |
useInputRadio | The radio field: the possibilities (provider, input options, else the model field's object map). |
getModelFieldPossibilitiesList | The model field's possibilities object map as a list (the fallback of the radio and enum preset fields). |
useInputVideo | useInput and useInputFile plus the player of the video fields. |
useInputFileDropZone | The drop zone of the pdf, video and attachment presets (click / Enter / Space opens the picker, a drop uploads like a picked file); options UseInputFileDropZoneOptions. |
toNumberValue | The 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>.
| Prop | Type | Default | Description |
|---|---|---|---|
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
| Prop | Type | Default | Description |
|---|---|---|---|
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.
| Prop | Type | Default | Description |
|---|---|---|---|
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.
| Prop | Type | Default | Description |
|---|---|---|---|
value? | string | null | — | The HTML to edit; rendered sanitised when it does not come from here. |
placeholder? | string | — | Placeholder of the empty editor. |
disabled? | boolean | false | Makes the editor read-only. |
toolbar? | SmartRichTextToolbar | LONG_TEXT_TOOLBAR | The 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
| Field | Type | Default | Description |
|---|---|---|---|
treeLevel | number | required | Nesting depth (0 at the top; nested object / array forms go one deeper). |
control | SmartAbstractControl | required | The 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 type | A field component used instead of the type's one. |
IInputFromFieldOptions<T>
| Field | Type | Default | Description |
|---|---|---|---|
model | T | required | The model instance the form was built from (its @Field metadata is read). |
fieldKey | string | required | The 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, ...). |
Related types
InputOptions<T>:IInputOptions & IInputFromFieldOptions<T>— WhatSmartInputtakes: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.
FieldType | Standard | Preset | Notes |
|---|---|---|---|
text | SmartInputText | SmartInputTextPreset | Text input. |
longText | SmartInputLongText | SmartInputLongTextPreset | Rich-text editor (SmartRichTextEditor); the value is HTML, shown sanitised. |
email | SmartInputEmail | SmartInputEmailPreset | type="email"; the form factory adds the email check. |
password | SmartInputPassword | SmartInputPasswordPreset | With possibilities: { strength: true } a strength meter sets the passwordStrength error until the password is strong. confirm: true adds a <key>Confirm field. |
int / float / currency | SmartInputInt / SmartInputFloat / SmartInputCurrency | …Preset | Number inputs (step 1 / 0.01 / 0.01); empty sets null. |
ints | SmartInputInts | SmartInputIntsPreset | A list of numbers, one row each plus a row to add. |
strings | SmartInputStrings | SmartInputStringsPreset | A list of strings (the preset as chips). |
flag | SmartInputFlag | SmartInputFlagPreset | Checkbox bound to a boolean. |
radio | SmartInputRadio | SmartInputRadioPreset | One radio per possibility; the value is its id. |
check | SmartInputCheck | SmartInputCheckPreset | One checkbox per possibility; the value is the list of checked ids. |
enum | SmartInputEnum | SmartInputEnumPreset | Differs: the standard renders checkboxes of the enum's keys (value: list of keys); the preset renders a <select> (value: one possibility id). |
date | SmartInputDate | SmartInputDatePreset | Native type="date", YYYY-MM-DD. |
dateWithEdit | SmartInputDateWithEdit | SmartInputDateWithEditPreset | SmartDateEdit (digit inputs) bound to the control. |
dateRange | SmartInputDateRange | SmartInputDateRangePreset | IDateRange value; the standard uses SmartDateRange, the preset two native date inputs. |
nip | SmartInputNip | SmartInputNipPreset | Adds the NIP check (invalidNip) to the control. |
pesel | SmartInputPesel | SmartInputPeselPreset | The form factory adds the pesel check; differs: the preset adds its own invalidPesel check to the control too (same message). |
phoneNumber | SmartInputPhoneNumber | SmartInputPhoneNumberPreset | type="tel"; the form factory adds the phoneNumber check. |
phoneNumberPl | SmartInputPhoneNumberPl | SmartInputPhoneNumberPlPreset | Exactly 9 characters (minlength / maxlength); the preset shows a +48 addon. |
color | SmartInputColor | SmartInputColorPreset | Native colour picker with a clear button. |
file | SmartInputFile | SmartInputFilePreset | Differs: the standard keeps the picked File as the value (no upload); the preset uploads it through the file service. |
attachment / pdf / video | SmartInputAttachment / SmartInputPdf / SmartInputVideo | …Preset (drop zones) | Upload through the file service; the value is the attachment the API returns. |
image | SmartInputImage | SmartInputImagePreset | .jpg,.png,.jpeg upload with a preview. |
logo | SmartInputLogo | SmartInputLogoPreset | Differs: the standard stores a base64 data: URL (no upload); the preset uploads like image. |
object | SmartInputObject | SmartInputObjectPreset | A nested SmartForm for the field's group (classType model), one tree level deeper. |
array | SmartInputArray | SmartInputArrayPreset | A nested SmartForm per item, an add button and drag-and-drop reordering (remove button in the preset only; possibilities.static disables changes). |
address | SmartInputAddress | SmartInputAddressPreset | A 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:
- the model possibilities provider (
modelPossibilitiesProvideronSmartProvider), 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 (anullorundefinedresult is ignored); - else
options.possibilities; - 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 forradioand the presetenum, a list as it is forcheck.
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 (
modelLabelProvideronSmartProvider) or the translation ofMODEL.<key>(seereact-provider). - A field with
info: '...'shows aSmartInfotooltip; a field withhide: true(for the mode) renders nothing. - Messages are shown once the control is touched, from its errors, in a fixed order:
required(which hidesconfirm),confirm,invalidNip,invalidUnique,email,phoneNumber,peselorinvalidPesel(one message),minlength,maxlength,min,max, andcustomMessage(its value is shown as is). The texts come fromINPUT.ERRORS.*translations.getInputErrorMessages(errors, t)returns that list for a custom message component.
Choosing the component of a field
options.componentonSmartInput(SmartFormfills it fromIFormOptions.inputComponents[fieldKey], and CRUD screens fromCrudFullConfig.inputComponents);- else
inputFieldComponents[type]registered onSmartProvider; - else the library's standard component for the type (
getDefaultInputFieldComponents()).
Replacing the Implementation
- Per field type, application-wide:
inputFieldComponentsonSmartProvidermaps aFieldTypeto a component takingSmartInputFieldProps. 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 }), oroptions.componentwhen you renderSmartInputyourself. - Validation messages: the
input-errorregistry key (components={{ 'input-error': SmartInputErrorPreset }}); the component receives{ errors }. SMART_PRESET_COMPONENTSregisters the preset field map andSmartInputErrorPresettogether 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.
| Returns | Type | Description |
|---|---|---|
inputRef | RefObject<HTMLInputElement | null> | Attach to the hidden file input. |
loading | boolean | true while a file uploads. |
percent | number | undefined | Upload progress (0–100), undefined when unknown. |
file | File | null | The picked File. |
onFileChange | (event: ChangeEvent<HTMLInputElement>) => void | The input's change handler: checks accept, uploads through the file service and sets the returned attachment as the value. |
addButtonOptions | IButtonOptions | IButtonOptions of the add / change button (opens the picker). |
showButtonOptions | IButtonOptions | IButtonOptions of the download / show button. |
deleteButtonOptions | IButtonOptions | IButtonOptions 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).
| Returns | Type | Description |
|---|---|---|
control | SmartAbstractControl<any> | null | The field's control (options.control). |
state | SmartControlState<any> | null | The control's live state (useControlState). |
value | any | The control's value. |
required | boolean | Whether the control reports required for an empty value (show a required mark). |
disabled | boolean | Whether the control is disabled. |
label | string | The field label: the label provider's, or MODEL.<key> translated. |
fieldKey | string | options.fieldKey. |
model | T | undefined | options.model. |
mode | string | undefined | options.mode. |
treeLevel | number | options.treeLevel (0 by default). |
fieldOptions | IFieldOptions | undefined | The merged field options. |
setValue | (value: unknown) => void | Sets the value as the user would: the control becomes dirty. |
markAsTouched | () => void | undefined | Marks the control as touched, as leaving the field does. |
autoFocus | boolean | Autofocus 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.classNamereaches 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.