Form

The <smart-form> component renders a reactive form driven by @Field() model decorators. It is a wrapper that delegates to FormStandardComponent by default and can be replaced via FORM_STANDARD_COMPONENT_TOKEN.


Usage

<smart-form
  [options]="options"
  (valueChange)="value.set($event)"
  (invokeSubmit)="onSubmit()"
/>
@if (value()?.firstName; as firstName) {
  <p>First name: {{ firstName }}</p>
}
@if (submitted()) {
  <p>Submitted</p>
}

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

FormComponent (<smart-form>)

Main wrapper. Holds all reactive-form logic: builds the form via FormFactory (or takes options.control), disables it while loading$ emits true, wraps the body in a <form> that emits invokeSubmit on submit and on Enter (keyup.enter), and emits valueChange, valuePartialChange and validChange from its own subscription to the form group. Renders FormStandardComponent by default. When FORM_STANDARD_COMPONENT_TOKEN is provided, renders the injected component via NgComponentOutlet, passing options, the built form and the class, and re-emitting the body's invokeSubmit.

FormStandardComponent (<smart-form-standard>)

Default concrete implementation. A container with dividers that renders one <smart-input> per control of the form (skipping missing and __smartDisabled controls), with the field's possibilities and inputComponents entry.

FormBaseComponent (abstract)

Abstract base directive. Extend it to build custom form implementations. It exposes:

  • inputs form (UntypedFormGroup, required), options (IFormOptions<T>, required) and cssClass (alias class)
  • the invokeSubmit output (OutputEmitterRef<any>) and submit(), which emits it with the form value
  • fields (the keys of form.controls), model, mode ('' when unset), possibilities, inputComponents, treeLevel, all read from the inputs
  • getUntypedFormControl(field) and the hooks afterSetForm() and afterSetOptions()

API

Inputs

InputTypeDefaultDescription
optionsInputSignal<IFormOptions<T>>requiredThe model, the mode and the other form options
classInputSignal<string>''Classes on the body container (cssClass input, alias class)

Outputs

OutputTypeDescription
invokeSubmitOutputEmitterRef<T>Emits the form value (form.value) on submit and on Enter.
valueChangeOutputEmitterRef<T>Emits the full form value on every change, and once when the form is ready
valuePartialChangeOutputEmitterRef<Partial<T>>Emits the values of the dirty controls (<key>Confirm controls left out) on every change
validChangeOutputEmitterRef<boolean>Emits form validity on every change

<smart-form> does not block the submit of an invalid form: keep validChange in state and check it before saving.

IFormOptions

FieldTypeDefaultDescription
modelTrequiredThe model instance (a @Model class); the factory builds one control per @Field the mode includes.
showbooleanrequiredRequired by the type; not read by the built-in implementations (pass true).
mode'create' | 'update' | string'create'Which fields and which mode options the factory uses. The inputs merge the options of the mode they receive ('' without one).
controlAbstractControl-A ready form group; without it the form is built from model by FormFactory.
loading$Observable<boolean>-Disables the whole form while it emits true, enables it on false.
uniqueProvider(values: Record<keyof T, any>) => Promise<boolean>-Async check of unique fields, passed to the factory.
possibilities{ [key: string]: WritableSignal<{ id: any; text: string; checked: boolean }[]> }{}Options of choice fields (radio, check, enum, ...), by field key.
inputComponents{ [key: string]: InputBaseComponentType<T> }{}Field components by field key, used instead of the type's component.
treeLevelnumber1Nesting depth; written to the host as the tree-level attribute.
fieldOptionsIFieldOptions-Not read by the built-in implementations; available to a custom implementation.
modelOptionsIModelOptions-Not read by the built-in implementations; available to a custom implementation.

FORM_STANDARD_COMPONENT_TOKEN

InjectionToken that allows replacing the default FormStandardComponent with a custom implementation. Provide a Type<FormBaseComponent<T>>; it renders inside the wrapper's <form>, so a type="submit" button submits it.

Extending the base class

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  signal,
  ViewEncapsulation,
} from '@angular/core';

import {
  FORM_STANDARD_COMPONENT_TOKEN,
  FormBaseComponent,
  FormComponent,
  IFormOptions,
  InputComponent,
} from '@smartsoft001/angular';
import { Field, FieldType, Model } from '@smartsoft001/models';

@Model({ titleKey: 'name' })
export class DocsAccount {
  @Field({ type: FieldType.text, create: true, required: true })
  name = '';

  @Field({ type: FieldType.email, create: true })
  email = '';
}

@Component({
  selector: 'docs-custom-form',
  template: `
    <div [class]="containerClasses()">
      <p class="docs-form__hint">All fields marked with * are required.</p>

      @for (field of fields; track field) {
        <div class="docs-form__row">
          <smart-input
            [options]="{
              treeLevel: treeLevel ?? 0,
              fieldKey: field,
              control: getUntypedFormControl(field),
              model: model,
              mode: mode,
            }"
          />
        </div>
      }

      <!--
        smart-form wraps this template in a <form>, so a submit button makes
        the wrapper emit its (invokeSubmit). Calling submit() from the base
        works too: the wrapper re-emits the body's invokeSubmit.
      -->
      <button type="submit" class="docs-form__submit">Create account</button>
    </div>
  `,
  imports: [InputComponent],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomFormComponent extends FormBaseComponent<DocsAccount> {
  // `cssClass` comes from the base (alias `class`): the wrapper hands the
  // consumer's class to it under that name.
  containerClasses = computed(() => {
    const classes = ['docs-form'];
    const extra = this.cssClass();
    if (extra) classes.push(extra);
    return classes.join(' ');
  });
}

@Component({
  selector: 'docs-form-custom-example',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormComponent],
  // The token swaps the standard form shell for the custom one everywhere
  // below this component, so consumers keep writing `<smart-form>`.
  providers: [
    { provide: FORM_STANDARD_COMPONENT_TOKEN, useValue: CustomFormComponent },
  ],
  template: `
    <smart-form
      [options]="options"
      (valueChange)="value.set($event)"
      (invokeSubmit)="submitted.set(true)"
    />
  `,
})
export class FormCustomExampleComponent {
  value = signal<DocsAccount | null>(null);
  submitted = signal(false);

  // `<smart-form>` builds the FormGroup from the @Field metadata through
  // FormFactory; the custom shell only decides how the fields are laid out.
  options: IFormOptions<DocsAccount> = {
    model: new DocsAccount(),
    show: true,
    mode: 'create',
  };
}

Field Rendering

Each field is rendered via <smart-input>. Per-field dispatch by FieldType is handled inside <smart-input> itself. See the angular-components-input skill for per-field details.

Preset

FormPresetComponent (<smart-form-preset>) is a styled, drop-in replacement for FormStandardComponent. It extends the standard component and reuses all of its logic (field iteration, statuses, submit-on-enter, and the value/valid/partial outputs on the wrapper). The preset only restyles the shell: the form root gets a vertical rhythm (smart:space-y-5) and each field row is wrapped in a data-role="field" element (with the field key on data-key); the root carries data-role="form".

The form preset does NOT restyle field internals. Each field is still rendered by <smart-input>, so to get the full styled look, register the input presets alongside it: provide FormPresetComponent for FORM_STANDARD_COMPONENT_TOKEN and INPUT_PRESET_FIELD_COMPONENTS for INPUT_FIELD_COMPONENTS_TOKEN, or register every preset at once with provideSmartPresets().

Providing only FORM_STANDARD_COMPONENT_TOKEN restyles the form layout but leaves the inputs in their default look. The preset keeps the inherited class alias, so <smart-form class="…"> still lands external classes on the form root.

Reference implementation

The example application under docs/examples/app never places <smart-form> by hand: the CRUD item page renders it from the @Field metadata, and the pieces below are what the form reads in any application.

  • docs/examples/app/libs/model/src/lib/note.model.ts: the @Field decorators the form is generated from, with create and update flags per mode, required repeated per mode and focused on the first input.
  • docs/examples/app/apps/web/src/app/app.config.ts: MODEL_VALIDATORS_PROVIDER registered even though the app adds no validators of its own, because the form factory injects it without a default and the form does not render without it.
  • docs/examples/app/apps/web/src/app/app.config.spec.ts: the test that the provider hands the base validators implied by the metadata back to the factory.
  • docs/examples/app/apps/web/src/app/translations.ts: the MODEL.<key> labels the rendered inputs show.

Source

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

SmartForm turns a model instance into a form. It asks the provider's FormFactory for a form of options.model in options.mode ('create' by default): one control per @Field the mode includes, with the validators the field options call for (see react-forms). Then it renders a body (the component registered under the form key, SmartFormStandard by default) with one SmartInput per control, and reports the value as the user types. Submitting, or pressing Enter in a single-line input, calls onInvokeSubmit(value) once. Pass a form you built yourself as options.control to skip the factory.


Usage

import { useState } from 'react';

import { Field, FieldType, Model } from '@smartsoft001/models';
import { IFormOptions, SmartForm } from '@smartsoft001/react';

// Each label is the `MODEL.<key>` translation: the library's dictionary
// already has `firstName` and `email`.
@Model({ titleKey: 'firstName' })
class Contact {
  @Field({ type: FieldType.text, create: true, required: true })
  firstName = '';

  @Field({ type: FieldType.email, create: true })
  email = '';
}

export function FormUsageExample() {
  // One model instance per form: a new instance rebuilds the form.
  const [model] = useState(() => new Contact());
  const [value, setValue] = useState<Contact | null>(null);
  const [submitted, setSubmitted] = useState(false);

  // `show` is required by the type; the form does not read it.
  const options: IFormOptions<Contact> = { model, show: true, mode: 'create' };

  return (
    <>
      <SmartForm
        options={options}
        onValueChange={setValue}
        // Called on submit, and on Enter in an input.
        onInvokeSubmit={() => setSubmitted(true)}
      />
      {value?.firstName && <p>First name: {value.firstName}</p>}
      {submitted && <p>Submitted</p>}
    </>
  );
}

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
SmartFormcomponentThe form of options.model, built by the form factory for options.mode ('create' by default) with options.uniqueProvider, or options.control when given.
SmartFormPresetcomponentStyled form variation (preset).
SmartFormStandardcomponentThe default form body: one input per control.
useFormBasehookWhat every form body shares: the fields to render, the options every input gets and submit().

The preset's class helpers (getFormShellClasses, getFormFieldClasses) are exported too, for a custom implementation that wants the preset look.

Props and Types

SmartFormProps<T = any>

The props of <SmartForm>.

PropTypeDefaultDescription
optionsIFormOptions<T>requiredThe model, the mode and the other form options.
className?string—Classes of the body container.
onInvokeSubmit?(value: any) => void—The form value, on submit or Enter.
onValueChange?(value: T) => void—The form value after every change.
onValuePartialChange?(value: Partial<T>) => void—The dirty controls' values, *Confirm left out.
onValidChange?(valid: boolean) => void—The form validity after every change.

SmartFormBaseProps<T = any>

The props of a form body: SmartFormStandard, SmartFormPreset or an implementation registered as components.form.

PropTypeDefaultDescription
formSmartFormGrouprequiredThe built form group.
optionsIFormOptions<T>requiredThe form options (treeLevel defaulted to 1).
className?string—Classes of the body container.
onInvokeSubmit?(value: any) => void—Call with the form value to submit (what useFormBase().submit does).

IFormOptions<T>

FieldTypeDefaultDescription
modelTrequiredThe model instance (a @Model class); a new instance builds a new form.
showbooleanrequiredRequired by the type; SmartForm does not read it (pass true).
treeLevel?number—Nesting depth; SmartForm defaults it to 1 and writes it as tree-level / data-tree-level.
control?SmartAbstractControl—A ready form; without it the form is built from model by the form factory.
mode?'create' | 'update' | string'create'Which fields and which mode options the factory uses: create, update, multiUpdate or a custom mode from customs. Pass it explicitly: the inputs merge the options of the mode they receive, and without mode they get none (the form is still built for create).
loading?boolean—Disables the whole form while true.
uniqueProvider?(values: Record<keyof T, any>) => Promise<boolean>—Async check of unique fields; resolve false to report invalidUnique.
possibilities?{ [key: string]: SmartPossibility[]; }{}Options of radio, check, enum or strings fields, by field key.
inputComponents?{ [key: string]: InputComponentType<T>; }{}Field components by field key, used instead of the type's component.
fieldOptions?IFieldOptions—Declared; SmartForm does not read it.
modelOptions?IModelOptions—Declared; SmartForm does not read it.
  • InputComponentType<T = any>: ComponentType<any> — A field component (takes SmartInputFieldProps).

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

Callbacks

CallbackWhenValue
onInvokeSubmitForm submit, or Enter in a single-line input (not in a textarea, the rich-text editor, a button or a select)form.value (disabled controls left out)
onValueChangeAfter every change, and once when the form is readyform.value
onValuePartialChangeAfter every change, and once when the form is readyThe values of the dirty controls, <key>Confirm controls left out
onValidChangeAfter every change, and once when the form is readyform.valid

SmartForm does not block the submit of an invalid form: check validity yourself (keep onValidChange in state, or build the form with useModelForm and call form.markAllAsTouched() before reading form.valid). Only the latest callbacks are used, so inline functions are fine.

Nested forms

object and array fields render a nested SmartForm one tree level deeper. A nested form renders a <div> instead of a <form> (HTML does not allow nested forms), and Enter in its inputs submits the outer form.

Labels

Field labels come from the modelLabelProvider of SmartProvider, or from the translation of MODEL.<fieldKey>: add those keys to translations (see react-provider).

Replacing the Implementation

SmartForm renders the body registered under the 'form' key of SmartProvider's components, and SmartFormStandard when nothing is registered. The body gets SmartFormBaseProps (the built form, the options, className, onInvokeSubmit); SmartForm itself keeps building the form, the <form> element, the callbacks and loading.

SmartFormPreset restyles only the shell (vertical rhythm, a data-role="field" wrapper with data-key per row, data-role="form" on the root). The fields keep their look unless the input presets are registered too, so register both.

SMART_PRESET_COMPONENTS registers both at once (see react-provider).

The useFormBase hook

What every form body shares: the fields to render, the options every input gets and submit(). The body re-renders on every change of the form, so a field added or removed by an enabled specification shows up at once. Bodies render a field when form.controls[field] exists and is not smartDisabled.

ReturnsTypeDescription
fieldsstring[]The control keys to render, in model order (a control removed and re-added by an enabled specification keeps its place; <key>Confirm follows <key>).
modelToptions.model.
modestringoptions.mode, '' when unset.
possibilities{ [key: string]: SmartPossibility[]; }options.possibilities ?? {}.
inputComponents{ [key: string]: InputComponentType<T>; }options.inputComponents ?? {}.
treeLevelnumber | undefinedoptions.treeLevel.
submit() => void | undefinedEmits onInvokeSubmit with the form value.
getControl(field: string) => SmartAbstractControl | undefinedThe control of field.

A form body receives the built form and the options; useFormBase gives the fields to render and submit():

import { useState } from 'react';

import { Field, FieldType, Model } from '@smartsoft001/models';
import {
  cn,
  IFormOptions,
  SmartForm,
  SmartFormBaseProps,
  SmartInput,
  SmartProvider,
  useFormBase,
} from '@smartsoft001/react';

@Model({ titleKey: 'name' })
export class DocsAccount {
  @Field({ type: FieldType.text, create: true, required: true })
  name = '';

  @Field({ type: FieldType.email, create: true })
  email = '';
}

export function CustomForm<T>(props: SmartFormBaseProps<T>) {
  // useFormBase gives the fields to render, what every input gets and
  // submit(), which reports the form value through onInvokeSubmit.
  const { fields, model, mode, treeLevel, getControl, submit } =
    useFormBase(props);

  return (
    <div className={cn('docs-form', props.className)}>
      <p className="docs-form__hint">All fields marked with * are required.</p>

      {fields.map((field) => {
        const control = getControl(field);

        // Skip the fields an `enabled` specification turned off.
        if (!control || control.smartDisabled) return null;

        return (
          <div key={field} className="docs-form__row">
            <SmartInput
              options={{
                treeLevel: treeLevel ?? 0,
                fieldKey: field,
                control,
                model,
                mode,
              }}
            />
          </div>
        );
      })}

      <button type="button" className="docs-form__submit" onClick={submit}>
        Create account
      </button>
    </div>
  );
}

// A module constant: a new object on every render would change the context.
const components = { form: CustomForm };

export function FormCustomExample() {
  const [model] = useState(() => new DocsAccount());
  const [value, setValue] = useState<DocsAccount | null>(null);
  const [submitted, setSubmitted] = useState(false);

  // SmartForm builds the form from the @Field metadata; the custom body only
  // decides how the fields are laid out.
  const options: IFormOptions<DocsAccount> = {
    model,
    show: true,
    mode: 'create',
  };

  // Every SmartForm below the provider renders its body with CustomForm.
  return (
    <SmartProvider components={components}>
      <SmartForm
        options={options}
        onValueChange={setValue}
        onInvokeSubmit={() => setSubmitted(true)}
      />
      {value?.name && <p>Name: {value.name}</p>}
      {submitted && <p>Account created</p>}
    </SmartProvider>
  );
}

A body skips controls that are missing or smartDisabled (fields an enabled specification turned off). It re-renders on every change of the form, so such fields appear and disappear at once.

Styling

  • SmartFormStandard stacks the fields with dividers (smart:dark: variants included); className is appended to the body container.

Source

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