...

/

Angular v.14 and Strong Typed Forms

Angular v.14 and Strong Typed Forms

Learn one of the most remarkable features of Angular v.14.

As of Angular v.14, reactive forms are now strictly typed by default.

Reactive forms weren't type-safe in earlier versions, meaning that the form controls' value type any type leaving our application exposed to possible errors.

Press + to interact
const username = new FormControl("my_username");
// usernameValue is of type any
const usernameValue = username.value;
console.log(usernameValue); // Output: "my_username"
// -----------------------------------------------------------------------
const age = new FormControl(29);
// ageValue is of type any
const ageValue = age.value;
console.log(ageValue); // Output: 29
//But if we reset the form control...
age.reset();
console.log(usernameValue); // Output: null
// ... this might introduce errors if we expect the value to be a string

By migrating to version 14, Angular CLI will automatically execute a built-in migration to replace all existing form classes (like FormGroup and FormControl) with their corresponding untyped version, like in the example below:

Press + to interact
//Before Angular 14
const registrationForm = new FormGroup({
username: new FormControl(''),
email: new FormControl(''),
});
//Updating to Angular 14 (after migration)
const registrationForm = new UntypedFormGroup({
username: new UntypedFormControl(''),
email: new UntypedFormControl(''),
});

Each untyped class (such as UntypedFormGroup) has the same properties and ...