Moving a large form to typed forms in Angular 14

Until Angular 14, form. value was any. You could read form. value. adress. city with a typo and TypeScript wouldn't say a word.

Until Angular 14, form.value was any. You could read form.value.adress.city with a typo and TypeScript wouldn’t say a word. Angular 14 finally gives reactive forms real types, and moving a big form over is a nice way to find bugs you didn’t know you had.

What the update does to your code

When you run ng update @angular/core@14, the migration doesn’t turn on types for you. It renames your existing classes to their untyped versions, so everything keeps compiling:

// before the update
form = new FormGroup({ name: new FormControl('') });

// after the update
form = new UntypedFormGroup({ name: new UntypedFormControl('') });

UntypedFormGroup behaves exactly like the old FormGroup. You then switch forms back to FormGroup, FormControl and FormBuilder one at a time, whenever you’re ready. That’s what makes it practical on a large app.

Why everything is string | null

The first surprise is this:

const email = new FormControl('');
// FormControl<string | null>

email.reset();
// email.value is now null

It’s not a bug. reset() has always set a control to null, and now the type says so. If you’d rather reset to the initial value, mark the control as non-nullable:

const name = new FormControl('', { nonNullable: true });
// FormControl<string>

name.reset();
// name.value is '' again

With FormBuilder you can do this for a whole group at once through fb.nonNullable, or by injecting NonNullableFormBuilder instead.

form = this.fb.nonNullable.group({
  name: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  age: [0],
  address: this.fb.nonNullable.group({
    street: [''],
    city: [''],
  }),
  newsletter: [false],
});

constructor(private fb: FormBuilder) {}

The types are inferred from the initial values, so age is a number and newsletter is a boolean without you writing a single interface.

value vs getRawValue()

The next surprise is that form.value has every field marked optional:

const value = this.form.value;
// value.name is string | undefined

That’s because disabled controls are left out of value. Angular can’t know at compile time which controls will be disabled, so every key might be missing. If you want all fields, disabled ones included, use getRawValue():

const raw = this.form.getRawValue();
// raw.address.city is string

For most submit handlers, getRawValue() is what you actually wanted all along.

The errors that showed up

This is where typed forms pay off. Code like this compiled fine before and is now an error:

this.form.patchValue({ age: '42' });  // age is a number
this.form.setValue({ name: 'Asha' });  // setValue needs every field
this.form.controls.phone;              // there's no phone control

The patchValue one is the most common in older code. Values often come from query params or an API that returns everything as strings, and they used to go straight into the form unchecked.

Reading controls gets better too. Instead of form.get(‘address.city’), which hands you a control that might be null, you can go through controls:

const city = this.form.controls.address.controls.city;
// FormControl<string>

It’s longer, but your editor autocompletes every step and a typo fails the build.

Dynamic forms

Not every form has fixed keys. For a list of values, type the FormArray:

const tags = new FormArray<FormControl<string>>([]);
tags.push(new FormControl('angular', { nonNullable: true }));

For a group where the keys come from data, like a permission per role, there’s a new FormRecord:

const permissions = new FormRecord<FormControl<boolean>>({});
permissions.addControl('canEdit', new FormControl(false, { nonNullable: true }));
permissions.addControl('canDelete', new FormControl(false, { nonNullable: true }));

FormGroup expects to know all its keys up front, so FormRecord is the right tool when you’re adding controls in a loop.

If you prefer writing the shape out, you can pass an interface of controls:

interface LoginForm {
  email: FormControl<string>;
  password: FormControl<string>;
  remember: FormControl<boolean>;
}

const login = new FormGroup<LoginForm>({
  email: new FormControl('', { nonNullable: true }),
  password: new FormControl('', { nonNullable: true }),
  remember: new FormControl(false, { nonNullable: true }),
});

How I’d migrate

Start with the forms that send data to the server, since a wrong type there is a real bug. Switch one form from Untyped* to the typed classes, add nonNullable where a reset should go back to the initial value, replace value with getRawValue() in the submit handler, and fix whatever the compiler complains about. Then move on to the next one. There’s no need to do the whole app in one PR.