Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 74 ยท Forms

Dynamic Forms and Custom Form Controls

Build Angular forms that change at runtime with FormArray rows and config-driven fields, multi-step wizards, file uploads and ControlValueAccessor widgets, with runnable stand-ins.

Not every form has a fixed shape. An invoice has as many line items as the user needs. A survey might be defined by an admin in a database, and its questions only exist at runtime. And sometimes the control you need isn't an <input> at all: a star rating, a color swatch picker, a tag editor. Angular's reactive forms handle all three cases, because the form model is built in TypeScript and can be assembled from data.

This lesson covers FormArray for repeating rows, building a form from a configuration object, and ControlValueAccessor, the small interface that lets any component act like a native form control.

The Angular code here is read-only, because the site can't run the Angular compiler. The runnable examples are stand-ins: plain TypeScript that models a rows array with a total, a config-driven form generator, and the accessor protocol between a control and a widget. They are not Angular's real classes.

Repeating rows with FormArray

A FormArray is a list of controls whose length can change. Its value is an array, and it is valid only when every row is valid. The usual pattern is a small factory function that creates one row, so you use it for the initial row and for every "Add" click:

TypeScript
import { CurrencyPipe } from '@angular/common';
import { Component, computed, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { toSignal } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-invoice',
  imports: [ReactiveFormsModule, CurrencyPipe],
  templateUrl: './invoice.component.html',
})
export class InvoiceComponent {
  private readonly fb = inject(FormBuilder);

  private createLine() {
    return this.fb.nonNullable.group({
      description: ['', Validators.required],
      quantity: [1, [Validators.required, Validators.min(1)]],
      price: [0, [Validators.required, Validators.min(0)]],
    });
  }

  protected readonly form = this.fb.nonNullable.group({
    customer: ['', Validators.required],
    lines: this.fb.array([this.createLine()]),
  });

  protected get lines() {
    return this.form.controls.lines;
  }

  protected addLine(): void {
    this.lines.push(this.createLine());
  }

  protected removeLine(index: number): void {
    if (this.lines.length > 1) {
      this.lines.removeAt(index);
    }
  }

  private readonly lineValues = toSignal(this.lines.valueChanges, { initialValue: this.lines.getRawValue() });
  protected readonly total = computed(() =>
    this.lineValues().reduce((sum, line) => sum + line.quantity * line.price, 0),
  );
}

push, insert(index, control), removeAt(index) and clear() change the array, and each call updates the parent's value and validity. In the template the array is a nested part of the form, and each row is a group:

HTML
<form [formGroup]="form">
  <input formControlName="customer" />

  <div formArrayName="lines">
    @for (line of lines.controls; track line; let i = $index) {
      <div [formGroupName]="i">
        <input formControlName="description" placeholder="Description" />
        <input formControlName="quantity" type="number" />
        <input formControlName="price" type="number" />
        <button type="button" (click)="removeLine(i)">Remove</button>
      </div>
    }
  </div>

  <button type="button" (click)="addLine()">Add line</button>
  <p>Total: {{ total() | currency }}</p>
</form>

Two details are worth remembering. First, track line tracks the control object itself (each row has its own), not its position. That way, removing the first row moves the other rows' DOM elements, with their focus and any other element state, instead of rebinding every row to a different control. See control flow for why track matters. Second, every row has a FormGroup of its own, so a row is "invalid" independently, which is how you can highlight the one bad line.

Here is the same behavior in a stand-in: an array of rows with push, removeAt, per-row validation and a derived total.

TypeScript Stand-in: rows you can add and remove

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that the form is invalid as long as any row is, and the total is derived from the rows, never stored separately. In real Angular the same total comes from valueChanges (as in the sketch above), or you can recompute it when you need it.

Building a form from configuration

When the fields come from data, you cannot write the group({...}) by hand. Instead you describe each field as an object and a function turns the list into controls:

TypeScript
type FieldConfig =
  | { type: 'text'; key: string; label: string; required?: boolean; minLength?: number }
  | { type: 'number'; key: string; label: string; min?: number; max?: number }
  | { type: 'select'; key: string; label: string; options: string[]; required?: boolean }
  | { type: 'checkbox'; key: string; label: string; mustBeChecked?: boolean };

function buildForm(fields: FieldConfig[]): FormRecord<FormControl<string | number | boolean>> {
  const form = new FormRecord<FormControl<string | number | boolean>>({});
  for (const field of fields) {
    const validators: ValidatorFn[] = [];
    if (field.type === 'text') {
      if (field.required) validators.push(Validators.required);
      if (field.minLength) validators.push(Validators.minLength(field.minLength));
    }
    // ...other types add their own validators
    const initial = field.type === 'checkbox' ? false : field.type === 'number' ? 0 : '';
    form.addControl(field.key, new FormControl(initial, { nonNullable: true, validators }));
  }
  return form;
}

FormRecord is the typed form group for dynamic keys: all controls share one type, and you can addControl and removeControl after creation. (A plain FormGroup is typed by its known keys, so it fits fixed forms better.) The template then picks the right element for each config entry with @switch:

HTML
<form [formGroup]="form">
  @for (field of fields; track field.key) {
    @switch (field.type) {
      @case ('select') {
        <label>{{ field.label }}
          <select [formControlName]="field.key">
            @for (option of field.options; track option) {
              <option [value]="option">{{ option }}</option>
            }
          </select>
        </label>
      }
      @case ('checkbox') {
        <label><input type="checkbox" [formControlName]="field.key" /> {{ field.label }}</label>
      }
      @default {
        <label>{{ field.label }} <input [type]="field.type" [formControlName]="field.key" /></label>
      }
    }
  }
</form>

This is the heart of every "form builder" and survey tool: data in, controls and markup out. Because the config is a discriminated union, TypeScript checks that every field type is handled, and a field cannot say options unless it is a select.

flowchart LR
  C["Config (JSON from API or code)"] --> B["buildForm()"]
  B --> M["FormRecord<br/>controls + validators"]
  C --> T["Template @switch<br/>input / select / checkbox"]
  M <-->|"formControlName"| T
  M --> V["value + validity"]

The same config produces both the form model and the markup that binds to it.

The stand-in below does both halves without a DOM: it builds a control per config entry, with defaults and validators, and "renders" each field as a line of markup text. A final check feeds sample values through the generated validators.

TypeScript Stand-in: a config-driven form generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If a field type arrives that the switch does not handle, the never assignment becomes a compile error: that is how you keep a config-driven form honest as new field types are added. For a hand-written schema, the compiler tells you at build time; for JSON from a server, you would validate it at runtime too.

Custom form controls with ControlValueAccessor

formControlName and [formControl] know how to talk to native inputs, checkboxes and selects. To make your own component work with them, and with ngModel, implement ControlValueAccessor (CVA). It is the adapter between the form model and the widget, and has four methods:

Method Called by Angular when Your job
writeValue(value) the model changes (initial value, setValue, reset) show the value in the widget
registerOnChange(fn) the control is connected store fn; call it when the user changes the value
registerOnTouched(fn) the control is connected store fn; call it when the user leaves or finishes
setDisabledState(isDisabled) the control is disabled or enabled disable or enable the widget

Here is a star-rating component. You register it with the NG_VALUE_ACCESSOR token so that Angular's form directives find it:

TypeScript
import { Component, forwardRef, signal } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-star-rating',
  template: `
    @for (star of stars; track star) {
      <button
        type="button"
        [disabled]="disabled()"
        [attr.aria-label]="star + ' stars'"
        [attr.aria-pressed]="star <= value()"
        (click)="choose(star)"
        (blur)="onTouched()"
      >{{ star <= value() ? 'โ˜…' : 'โ˜†' }}</button>
    }
  `,
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => StarRatingComponent), multi: true },
  ],
})
export class StarRatingComponent implements ControlValueAccessor {
  protected readonly stars = [1, 2, 3, 4, 5];
  protected readonly value = signal(0);
  protected readonly disabled = signal(false);

  private onChange: (value: number) => void = () => {};
  protected onTouched: () => void = () => {};

  writeValue(value: number | null): void {
    this.value.set(value ?? 0);
  }
  registerOnChange(fn: (value: number) => void): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
  setDisabledState(isDisabled: boolean): void {
    this.disabled.set(isDisabled);
  }

  protected choose(star: number): void {
    this.value.set(star);
    this.onChange(star);
    this.onTouched();
  }
}

Used in a form it looks like any other control: <app-star-rating formControlName="rating" />. It is the provider system at work: NG_VALUE_ACCESSOR is a multi token, and Angular's FormControlName directive injects all accessors found on the element and picks the matching one. (forwardRef is needed because the class is referenced inside its own decorator, before the class exists.)

A few rules prevent classic bugs:

  • Call onChange only for user-driven changes. writeValue must update the display without calling onChange, or you create an endless loop between model and widget.
  • writeValue can receive null (a plain control's reset()), so handle it.
  • A CVA doesn't validate by itself. Put validators on the control (Validators.required), or implement Validator to ship validation with the widget.
  • Call onTouched so that "show the error after touched" logic works for your widget too.
flowchart LR
  FC["FormControl<br/>value, status, touched"] -->|"writeValue(v)"| W["Your widget"]
  W -->|"onChange(v)"| FC
  W -->|"onTouched()"| FC
  FC -->|"setDisabledState(d)"| W

The accessor is a two-way channel: the model pushes values in, the widget reports changes and touches out.

The last stand-in plays both roles. A mini control connects to an accessor, exactly as the form directives do when they see formControlName, and the star widget (drawn as text) implements the four methods.

TypeScript Stand-in: the ControlValueAccessor protocol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The important line is the one that is absent: when setValue(1) is called from code, the widget updates itself but does not report a user change. That one-way rule for writeValue is what keeps model and widget from feeding each other forever. In current Angular you can also avoid the provider boilerplate by injecting NgControl and assigning ngControl.valueAccessor = this in the constructor, but the four methods stay the same.

Multi-step forms (wizards)

Long forms are easier to finish when they are split into steps. The reliable way to build one in Angular is one FormGroup per step inside a parent group. The parent holds the whole answer, each step validates itself, and "Next" is allowed only when the current step is valid.

TypeScript
// signup-wizard.ts
import { Component, computed, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-signup-wizard',
  imports: [ReactiveFormsModule],
  template: `
    <ol aria-label="Progress">
      @for (name of stepNames; track name; let i = $index) {
        <li [attr.aria-current]="i === step() ? 'step' : null">{{ name }}</li>
      }
    </ol>

    <form [formGroup]="form" (ngSubmit)="submit()">
      @switch (step()) {
        @case (0) {
          <div formGroupName="account">
            <input formControlName="email" type="email" aria-label="Email" />
            <input formControlName="password" type="password" aria-label="Password" />
          </div>
        }
        @case (1) {
          <div formGroupName="profile">
            <input formControlName="name" aria-label="Name" />
          </div>
        }
        @case (2) {
          <p>Review: {{ form.getRawValue() | json }}</p>
        }
      }

      <button type="button" (click)="back()" [disabled]="step() === 0">Back</button>
      @if (step() < stepNames.length - 1) {
        <button type="button" (click)="next()">Next</button>
      } @else {
        <button type="submit" [disabled]="form.invalid">Create account</button>
      }
    </form>
  `,
})
export class SignupWizard {
  private readonly fb = inject(FormBuilder);
  protected readonly stepNames = ['Account', 'Profile', 'Review'];
  protected readonly step = signal(0);

  protected readonly form = this.fb.nonNullable.group({
    account: this.fb.nonNullable.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    }),
    profile: this.fb.nonNullable.group({
      name: ['', Validators.required],
    }),
  });

  private readonly stepGroups = ['account', 'profile'] as const;

  next(): void {
    const key = this.stepGroups[this.step()];
    const group = key ? this.form.controls[key] : null;
    if (group && group.invalid) {
      group.markAllAsTouched(); // show the errors for this step only
      return;
    }
    this.step.update(s => s + 1);
  }

  back(): void {
    this.step.update(s => Math.max(0, s - 1));
  }

  submit(): void {
    if (this.form.valid) {
      console.log(this.form.getRawValue());
    }
  }
}

Two details deserve attention. @switch removes the inactive step's inputs from the DOM, but the controls still exist in the form model, so values survive going back and forth. And markAllAsTouched() on the current step shows its errors without nagging about steps the user has not reached. If you want a ready-made UI with a header and keyboard support, Angular Material's stepper and the CDK stepper (Angular Material and the CDK) use the same one-group-per-step idea.

TypeScript A wizard: validate the current step before moving on

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

File inputs and upload progress

A file input is different from other controls: its value is a FileList, and a browser does not allow you to set it from code. So you do not bind it with formControlName. Listen to (change), keep the chosen File in a signal or in a control you set yourself, and send it with FormData.

TypeScript
// avatar-upload.ts
import { Component, inject, signal } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';

@Component({
  selector: 'app-avatar-upload',
  template: `
    <input type="file" accept="image/png,image/jpeg" (change)="choose($event)" aria-label="Avatar" />
    @if (error()) { <p role="alert">{{ error() }}</p> }
    @if (file(); as f) {
      <p>{{ f.name }} ({{ (f.size / 1024).toFixed(0) }} KB)</p>
      <button type="button" (click)="upload()" [disabled]="uploading()">Upload</button>
    }
    @if (uploading()) {
      <progress [value]="progress()" max="100"></progress> {{ progress() }}%
    }
  `,
})
export class AvatarUpload {
  private readonly http = inject(HttpClient);
  protected readonly file = signal<File | null>(null);
  protected readonly error = signal('');
  protected readonly progress = signal(0);
  protected readonly uploading = signal(false);

  choose(event: Event): void {
    const picked = (event.target as HTMLInputElement).files?.[0] ?? null;
    this.error.set('');
    if (picked && picked.size > 2 * 1024 * 1024) {
      this.error.set('Please pick a file under 2 MB.');
      this.file.set(null);
      return;
    }
    this.file.set(picked);
  }

  upload(): void {
    const file = this.file();
    if (!file) return;
    const body = new FormData();
    body.append('avatar', file); // do NOT set Content-Type yourself: the browser adds the boundary

    this.uploading.set(true);
    this.http.post('/api/avatar', body, { reportProgress: true, observe: 'events' }).subscribe({
      next: event => {
        if (event.type === HttpEventType.UploadProgress && event.total) {
          this.progress.set(Math.round((100 * event.loaded) / event.total));
        } else if (event.type === HttpEventType.Response) {
          this.uploading.set(false);
        }
      },
      error: () => {
        this.uploading.set(false);
        this.error.set('Upload failed. Please try again.');
      },
    });
  }
}

Remember the rules from earlier lessons: reportProgress: true with observe: 'events' is what makes progress events appear, and upload progress needs the XHR backend, so an app that uses withFetch() (HttpClient: Requests and Responses) will not receive UploadProgress. The accept attribute and the size check are conveniences; the server must validate type and size itself.

TypeScript Validating a file and tracking progress events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

When to use which

  • Fixed form, known fields: a plain FormGroup from FormBuilder.
  • A repeating part: FormArray, with one factory function for a row and track on the control object.
  • Fields decided at runtime: a config array, FormRecord for the model and @switch for the markup.
  • A new kind of input: a ControlValueAccessor so that validation, touched and disabled all keep working.
  • For new forms, you may also meet the experimental signal forms, which approach all of this from a signal model.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the value of a FormArray look like?

    A FormGroup gives an object and a FormArray gives an array. Adding or removing a row (push, removeAt) updates the array's value and validity.
  2. 2. Why is "track line" (the control object) better than "track $index" for form rows that can be removed?

    Tracking by index rebinds elements to different controls when a row is removed from the middle. Tracking the control keeps one element per row.
  3. 3. Which type is meant for forms whose control keys are only known at runtime?

    FormRecord is a typed group for dynamic keys, where all controls share the same type, and you can add or remove controls after creation.
  4. 4. In a ControlValueAccessor, which method should NOT call the onChange callback?

    onChange reports user-driven changes. Calling it from writeValue would echo the model's own update back to it and can loop.
  5. 5. How does Angular's form directive find your custom component's accessor?

    Providing NG_VALUE_ACCESSOR (with useExisting and forwardRef) on the component lets formControlName and ngModel inject it.

Summary

  • FormArray holds a changeable list of controls; build rows with a factory function, change it with push, insert, removeAt and clear, and track the control objects in @for.
  • To generate forms from data, describe fields as a discriminated union, build a FormRecord from it, and render each field with @switch; the never check keeps every type handled.
  • ControlValueAccessor (writeValue, registerOnChange, registerOnTouched, setDisabledState) makes any component behave like a native form control; register it with NG_VALUE_ACCESSOR.
  • writeValue must not call onChange, and must tolerate null.
  • Build a wizard with one FormGroup per step inside a parent group, validate and markAllAsTouched() the current step before "Next".
  • A file input cannot be bound with formControlName: read files from (change), send a FormData, and use reportProgress with observe: 'events' for progress (not available with withFetch()).
  • The Angular code is read-only; the rows array, the generator and the accessor protocol here are stand-ins.

Next: RxJS Essentials: Observables