How To Build a Strongly Typed Angular Super Form

Enforce Form Control Types via your Data Models

How To Build a Strongly Typed Angular Super Form

Create your First Super Form in Angular (📷: Admec)

Typed Forms

“Typed forms ensure that the values inside of form controls, groups, and arrays are type-safe across the entire API surface. This enables safer forms, especially for deeply nested complex cases.” Angular Blog

As of Angular 14 FormControls and FormGroups are now strongly typed:

Notice with the example above, we can emit the value of this.formGroup.getRawValue() directly via addShirtToCartRequested because the type of the return value matches our Item<Shirt> interface. The addition of strong types in Angular forms allows us to write code faster and with fewer bugs.

Additionally, the editor can now provide us with type-ahead suggestions for our form’s value property:

Type-Ahead Suggestions with Angular 14 Forms

The type-safe form value will cause the compiler to emit errors when we access a property that doesn’t exist or use a property in a way that conflicts with its type definition.

There’s one piece that’s missing from our example above. What if we wanted to enforce that formGroup matches the Item<Shirt> interface when formGroup is declared?

Oops! We forgot a FormControl!

Wouldn’t it be nice if we were able to explicitly type formGroup to match our Item<Shirt> interface at declaration time? Have no fear, Super Forms are here!

Super Forms

A Super Form is a contrived term to describe a FormGroup interface that matches the interface of a data model. Thanks to this ‘Bonus’ snippet from Netanel Basel, typing the inputs and outputs of a form in Angular 14 can be accomplished by introducing a nifty ControlsOf type:

Now you can enforce the type of formGroup at declaration time and give your FormGroup superpowers by using ControlsOf like so:

Now, if you forget to include a property in formGroup you’ll get an error at declaration time. Here’s what that error may look like:

Stack Blitz

A full example that demonstrates an Angular 14 Super Form can be found in the embedded Stack Blitz included below:

If you’d like to learn more about Angular typed forms, please see the Angular release blog post. Good luck!

Want to connect? If you found the information in this tutorial valuable, follow me on Twitter.