Exciting News for 2022 (Angular 14): Enhanced Typed Reactive Forms
Great news with the recent Angular update! Strict types are now available for reactive forms, eliminating the need for workarounds.
If you're using the formBuilder
service to create your forms, you can easily assign a strict type like this:
type myType = 'typeA' | 'typeB' | 'typeC';
public myForm = this.fb.control<myType>('typeA');
If you prefer creating a formGroup
without relying on the formBuilder
service, here's how you can do it:
interface User {
name: FormControl<string>;
email: FormControl<string>;
isAdmin: FormControl<boolean>;
}
public user: FormGroup<User> = new FormGroup<User>({
name: new FormControl('', {nonNullable: true}),
email: new FormControl('', {nonNullable: true}),
isAdmin: new FormControl(false, {nonNullable: true}),
});
Note that not specifying the nonNullable
attribute may lead to errors in your template regarding values being null
, especially when binding form control values.
Angular now automatically checks the type system even if you don't explicitly define the type, as demonstrated here:
const cat = new FormGroup({
name: new FormGroup({
first: new FormControl('Barb'),
last: new FormControl('Smith'),
}),
lives: new FormControl(9),
});
// Type-checking for forms values!
// TS Error: Property 'substring' does not exist on type 'number'.
let remainingLives = cat.value.lives.substring(1);
// Optional and required controls are enforced!
// TS Error: No overload matches this call.
cat.removeControl('lives');
// FormGroups are aware of their child controls.
// name.middle is never on cat
let catMiddleName = cat.get('name.middle');
For more information, check out the Angular 14 release update on their blog here