0 day streak
javascript / intermediate
Snippet

Type-safe Reactive Forms

Since Angular 14, Reactive Forms are strictly typed. Using interfaces for FormGroups ensures that you get compile-time errors if you access a control that doesn't exist or assign a value of the wrong type. The 'nonNullable' option prevents the value from becoming null when the form is reset.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface UserForm {
email: FormControl<string>;
age: FormControl<number | null>;
}
@Component({...})
export class MyComponent {
loginForm = new FormGroup<UserForm>({
email: new FormControl('', { nonNullable: true }),
age: new FormControl(null)
});
submit() {
const emailValue: string = this.loginForm.controls.email.value;
}
}
angular
Breakdown
1
new FormGroup<UserForm>(...)
Applies strict TypeScript types to the form structure.
2
{ nonNullable: true }
Ensures the control value reverts to the initial value instead of null on reset.