Full answer
Dynamic forms suit admin tools, surveys, and onboarding where fields change often or come from the back end. They trade type safety and flexibility of layout for speed of change, so use them where the form really is data.
Design:
- Typed configuration: a discriminated union such as
{ type: 'text' | 'number' | 'select' | 'checkbox'; key; label; required?; options?; minLength?; visibleWhen?: { key; equals } }. The compiler checks that aselecthas options. - Builder: a pure function
buildForm(fields)returns aFormGroupwith oneFormControlper field. A map of validator factories turns config (required,minLength,pattern) intoValidators. Keeping it pure makes it easy to unit test. - Rendering: a loop with
@switch (field.type)renders the right input. Each control gets a label, aforandidpair, and error messages linked witharia-describedby. A genericFieldComponentper type keeps the template short. - Conditional fields: a field with
visibleWhenis shown only when another control has a value. Hidden controls should be disabled, so their validators do not block submit and they are excluded fromgetRawValue()filters. AvalueChangessubscription (or a computed overtoSignal(form.valueChanges)) togglesdisable()andenable(). - Types: the form value is
Record<string, unknown>, which is the cost of dynamic forms. Narrow at the boundary with a parsing function or a schema (Zod, Valibot) before sending to the API. - Server config: validate the config itself on load, and version it. Never trust it to contain executable code. Validators come from your own map, never from strings evaluated at run time.
When not to use it: forms with complex layout, cross-field business rules, or custom UX are clearer as normal code. Often a hybrid is best: a generic renderer for simple sections and hand-written components for special fields.
typescript
// file: dynamic-form.ts
import { Component, input } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
import { toSignal } from '@angular/core/rxjs-interop';
interface BaseField {
key: string;
label: string;
required?: boolean;
visibleWhen?: { key: string; equals: unknown };
}
export type Field =
| (BaseField & { type: 'text'; minLength?: number })
| (BaseField & { type: 'number'; min?: number })
| (BaseField & { type: 'select'; options: string[] })
| (BaseField & { type: 'checkbox' });
export function validatorsFor(field: Field): ValidatorFn[] {
const list: ValidatorFn[] = [];
if (field.required) {
list.push(field.type === 'checkbox' ? Validators.requiredTrue : Validators.required);
}
if (field.type === 'text' && field.minLength) {
list.push(Validators.minLength(field.minLength));
}
if (field.type === 'number' && field.min !== undefined) {
list.push(Validators.min(field.min));
}
return list;
}
export function buildForm(fields: Field[]): FormGroup<Record<string, FormControl<unknown>>> {
const controls: Record<string, FormControl<unknown>> = {};
for (const field of fields) {
const initial = field.type === 'checkbox' ? false : '';
controls[field.key] = new FormControl<unknown>(initial, { nonNullable: true, validators: validatorsFor(field) });
}
const form = new FormGroup(controls);
applyVisibility(form, fields);
form.valueChanges.subscribe(() => applyVisibility(form, fields));
return form;
}
function applyVisibility(form: FormGroup<Record<string, FormControl<unknown>>>, fields: Field[]): void {
for (const field of fields) {
if (!field.visibleWhen) {
continue;
}
const control = form.controls[field.key];
const visible = form.controls[field.visibleWhen.key]?.value === field.visibleWhen.equals;
if (visible && control.disabled) {
control.enable({ emitEvent: false });
} else if (!visible && control.enabled) {
control.disable({ emitEvent: false });
}
}
}
@Component({
selector: 'app-dynamic-form',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submitted = form.getRawValue()">
@for (field of fields(); track field.key) {
@if (form.controls[field.key].enabled) {
<div>
<label [for]="field.key">{{ field.label }}</label>
@switch (field.type) {
@case ('select') {
<select [id]="field.key" [formControlName]="field.key">
@for (option of optionsOf(field); track option) {
<option [value]="option">{{ option }}</option>
}
</select>
}
@case ('checkbox') {
<input type="checkbox" [id]="field.key" [formControlName]="field.key" />
}
@case ('number') {
<input type="number" [id]="field.key" [formControlName]="field.key" />
}
@default {
<input type="text" [id]="field.key" [formControlName]="field.key" />
}
}
@if (form.controls[field.key].touched && form.controls[field.key].invalid) {
<small role="alert">{{ field.label }} is not valid</small>
}
</div>
}
}
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
`,
})
export class DynamicFormComponent {
readonly fields = input.required<Field[]>();
form = new FormGroup<Record<string, FormControl<unknown>>>({});
submitted: unknown = null;
ngOnInit(): void {
this.form = buildForm(this.fields());
}
optionsOf(field: Field): string[] {
return field.type === 'select' ? field.options : [];
}
}
// file: dynamic-form.spec.ts
import { buildForm, Field } from './dynamic-form';
describe('buildForm', () => {
const fields: Field[] = [
{ type: 'text', key: 'name', label: 'Name', required: true, minLength: 3 },
{ type: 'checkbox', key: 'hasMentor', label: 'Has a mentor' },
{ type: 'text', key: 'mentorName', label: 'Mentor name', required: true, visibleWhen: { key: 'hasMentor', equals: true } },
];
it('applies validators from the configuration', () => {
const form = buildForm(fields);
form.controls['name'].setValue('Al');
expect(form.controls['name'].errors?.['minlength']).toBeTruthy();
form.controls['name'].setValue('Asha');
expect(form.controls['name'].valid).toBeTrue();
});
it('disables a hidden field so it does not block the form', () => {
const form = buildForm(fields);
form.controls['name'].setValue('Asha');
expect(form.controls['mentorName'].disabled).toBeTrue();
expect(form.valid).toBeTrue();
form.controls['hasMentor'].setValue(true);
expect(form.controls['mentorName'].enabled).toBeTrue();
expect(form.valid).toBeFalse();
form.controls['mentorName'].setValue('Ravi');
expect(form.valid).toBeTrue();
});
});Angular 20.3, strict template check passes, and a Karma spec tests the builder (validators and conditional disabling).
Key points
- Describe fields as a typed discriminated union. Build the group in a pure function.
- Map config to validators from a fixed set, never evaluate strings.
- `@switch` renders by field type. Disable hidden conditional controls.
- The value type is loose. Validate at the boundary. Use code for complex forms.
Common mistakes
- Leaving hidden controls enabled, so their validators block submit.
- Evaluating expressions from config with `eval`, which is a security hole.
- Using dynamic forms for a form that never changes.
Follow-ups
- How would you add a cross-field rule such as "end date after start date"?
- How would you support nested groups and repeating sections with `FormArray`?
- How do you provide accessible error messages for generated fields?
Tips
- Start with when dynamic forms are the right choice.
- Say that validators come from a closed set. It shows security thinking.
- Mention the typing limit honestly.
Evaluation rubric
- Builds a typed configuration and a pure builder.
- Handles conditional fields and rendering correctly.
- Covers accessibility, security, and trade-offs.