Sub topic 19
Building Dynamic Forms at Runtime
Some forms don't know their full shape at compile time. A checkout form may add a "company name" field only for business customers. A settings page may build one checkbox per notification channel returned by an API. This chapter covers the tools Angular gives you for changing a form's structure after you create it: addControl, removeControl, setControl, and FormRecord.
This chapter assumes you already know typed FormGroup and FormControl, NonNullableFormBuilder, template binding with formControlName, and the FormArray chapter. Repeating rows are covered there, so this chapter focuses on controls identified by name.
Three Shapes of Dynamic Form
Before you write code, decide which of three situations you are in.
| Situation | Keys known at compile time? | Control types | Best fit |
|---|---|---|---|
| A few fields appear or disappear | Yes, as optional keys | Mixed | `FormGroup` with optional properties |
| Keys come from data (IDs, config) | No | All the same type | `FormRecord<T>` |
| An ordered list of similar entries | No (indexed) | All the same type | `FormArray<T>` |
Optional Controls in a Typed FormGroup
In a strictly typed FormGroup, addControl and removeControl are only allowed for keys you declared as optional. The type system protects your required fields.
import { FormControl, FormGroup, Validators } from '@angular/forms';
interface ContactControls {
email: FormControl<string>;
phone?: FormControl<string>;
}
const contact = new FormGroup<ContactControls>({
email: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.email] }),
});
function setPhoneRequired(required: boolean): void {
if (required) {
contact.addControl(
'phone',
new FormControl('', { nonNullable: true, validators: [Validators.required] }),
);
} else {
contact.removeControl('phone');
}
}
setPhoneRequired(true);
console.log(Object.keys(contact.controls)); // ['email', 'phone']
console.log(contact.valid); // false: phone is required and empty
setPhoneRequired(false);
console.log(Object.keys(contact.controls)); // ['email']
// contact.removeControl('email'); // Compile error: 'email' is not an optional key
// contact.addControl('fax', new FormControl('')); // Compile error: unknown keyBecause phone is optional, contact.getRawValue() has the type { email: string; phone?: string }. Your submit code has to handle phone being absent, and that's the behavior you want here.
Both addControl and removeControl recalculate the group's value and validity, and they emit on valueChanges and statusChanges. Pass { emitEvent: false } as the last argument when you're making a batch of changes and don't want subscribers to fire on each one.
FormRecord for Data-Driven Keys
When the keys come from data, such as channel IDs, product codes, or permission names, you can't list them in an interface. FormRecord<TControl> is a FormGroup whose keys are any string and whose controls all share one type.
import { Component } from '@angular/core';
import { FormControl, FormRecord, ReactiveFormsModule } from '@angular/forms';
interface Channel {
id: string;
label: string;
defaultOn: boolean;
}
@Component({
selector: 'app-notification-prefs',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="prefs" (ngSubmit)="save()">
@for (channel of channels; track channel.id) {
<label>
<input type="checkbox" [formControlName]="channel.id" />
{{ channel.label }}
</label>
}
<button type="submit">Save</button>
<button type="button" (click)="dropSms()">Remove SMS</button>
</form>
`,
})
export class NotificationPrefsComponent {
prefs = new FormRecord<FormControl<boolean>>({});
channels: Channel[] = [];
constructor() {
this.syncChannels([
{ id: 'email', label: 'Email', defaultOn: true },
{ id: 'sms', label: 'Text message', defaultOn: false },
{ id: 'push', label: 'Push notification', defaultOn: true },
]);
}
syncChannels(next: Channel[]): void {
const nextIds = new Set(next.map((c) => c.id));
for (const id of Object.keys(this.prefs.controls)) {
if (!nextIds.has(id)) {
this.prefs.removeControl(id, { emitEvent: false });
}
}
for (const channel of next) {
if (!this.prefs.controls[channel.id]) {
this.prefs.addControl(
channel.id,
new FormControl(channel.defaultOn, { nonNullable: true }),
{ emitEvent: false },
);
}
}
this.channels = next;
this.prefs.updateValueAndValidity();
}
dropSms(): void {
this.syncChannels(this.channels.filter((c) => c.id !== 'sms'));
}
save(): void {
// Type: Partial<Record<string, boolean>>-like object, e.g. { email: true, push: true }
console.log(this.prefs.getRawValue());
}
}syncChannels follows a reusable pattern. It removes the controls that are no longer wanted, adds the missing ones, keeps the controls that already exist (so their values and touched state survive), and then runs a single updateValueAndValidity() at the end. FormBuilder and NonNullableFormBuilder also have a record() method if you prefer to create records through the builder.
Adding, Replacing, and Registering
The methods that change structure look alike, but they behave differently.
| Method | If the key already exists | Updates value/validity | Typical use |
|---|---|---|---|
| `addControl(name, ctrl)` | Does nothing; keeps the old control | Yes | Add a control only if it's missing |
| `setControl(name, ctrl)` | Replaces the old control | Yes | Swap in a control with different validators |
| `registerControl(name, ctrl)` | Does nothing; keeps the old control | No | Low-level; directives use it internally |
| `removeControl(name)` | Removes it | Yes | Drop a field |
| `contains(name)` | Returns `true` only if present and enabled | n/a | Check before adding or rendering |
Gotchas
addControl Silently Ignores Duplicates
Calling addControl('phone', newControl) when phone already exists keeps the old control and throws away newControl. If you meant to change its validators or initial value, use setControl, or call setValidators followed by updateValueAndValidity on the existing control.
contains Ignores Disabled Controls
contains('sms') returns false for a control that exists but is disabled. If you use it as an "already added?" check, you'll call addControl on a disabled control, and that call does nothing. To test whether the key exists at all, check controls[name] instead.
Index Access Can Be Undefined
prefs.controls['anything'] is typed as FormControl<boolean>, but at runtime it can be undefined. Turn on noUncheckedIndexedAccess in tsconfig.json, or always guard the lookup, as syncChannels does.
Replacing Controls Breaks Old Subscriptions
A subscription to prefs.controls['email'].valueChanges stays attached to that specific control instance. If setControl replaces the control, the subscription keeps listening to the old object, which no longer changes. Subscribe to the parent's valueChanges instead, or subscribe again after each replacement.
Don't Use FormRecord for Mixed Shapes
FormRecord only types one control kind. If you find yourself writing FormRecord<AbstractControl<any>>, you have lost type safety. Use a FormGroup with optional keys, or nest several records.
Exercise
A permissions screen loads a list of permission names from the server and shows one checkbox per name. An admin can later reload the list, which may add or remove names. Users must not lose checkbox values they've already changed for permissions that are still in the list. Which container do you use, and how do you apply a reloaded list?
Show answer
Use FormRecord<FormControl<boolean>>, because the keys are data-driven strings and every control is a boolean checkbox. On reload, remove the controls whose names are no longer in the list, call addControl only for names that have no control yet, and leave existing controls alone so their values and dirty/touched state survive. Pass { emitEvent: false } during the batch, call updateValueAndValidity() once at the end, and update the template's source list in the same method so no formControlName points at a missing control.
Exercise
You call form.addControl('discount', new FormControl(0, { validators: [Validators.max(50)] })) on a group that already has a discount control with no validators. Why does entering 80 still pass validation, and what should you call instead?
Show answer
addControl does nothing when the key already exists, so the original discount control without validators stays in place. Use form.setControl('discount', ...) to replace it, or call form.controls.discount.setValidators(Validators.max(50)) followed by form.controls.discount.updateValueAndValidity() on the existing control.