Angular 14 ships with typed reactive forms, and it's just great. Type inference, backward compatibility, fine-tuning options, and user-defined type definitions - it's all there. It's been a long wait, but it was worth it!
Type inference and backward compatibility
Truth to tell, I noticed the feature when I ran into strange bugs after updating to Angular 14. As it turns out, Angular determines the type of the form controls by their default values:
const name = new FormControl(''); // --> string | null const truth = new FormControl(true); // --> boolean | nullAwesome! However, after updating to Angular 14, you'll probably have to fix zillions of type errors. In the meantime, you can use UntypedFormControl
instead of FormControl
.
Fine-tuning
The inferred type string | null
puzzled me at first. You can get rid of it by adding an option:
This guarantees the form control is never null. The null value is confusing because form controls reflect the user input, and users never can input null values. Even if they don't input anything, it's still an empty string. However, as Netanal Basal explains, FormControl.reset()
sets the value to null unless you add the nonNullable
attribute.
User-defined typings
FormControl
has become a generic type. So you can override the default by passing a type parameter:
This also works for entire FormGroups
, as Netanal Basal reports::
Wrapping it up
In a nutshell, Angular 14 finally ships with simple and valuable typed reactive forms. You'll love it!
This article is merely a litte teaser. Please read the full story at Netanal Basal's blog.