As of Angular 14, reactive forms are strictly typed by default (Typed Forms). This is great. I have implemented a simple login form like below
form = this.fb.group({
username: ['', [Validators.required]],
password: ['', [Validators.required]],
rememberMe: [true]
});
submit() {
this.authenticationService.login(this.form.value).subscribe();
And in the service I have
login(data: { username: string; password: string; rememberMe: boolean }): Observable<any> {
// Logic to login here
}
Typescript infers the type of form
to be
form: FormGroup<{username: FormControl<string>, password: FormControl<string>, rememberMe: FormControl<boolean>}>
which looks good. The problem arises with this.form.value
that has a type Partial<{ username: string; password: string; rememberMe: boolean; }>
. This causes typescript to throw an error
Argument of type 'Partial<{ username: string; password: string; rememberMe: boolean; }>' is not assignable to parameter of type '{ username: string; password: string; rememberMe: boolean; }'. Property 'username' is optional in type 'Partial<{ username: string; password: string; rememberMe: boolean; }>' but required in type '{ username: string; password: string; rememberMe: boolean; }'.
Is there a way while declaring the formgroup to indicate that the field will be available in the formgroup value. Currently I am typecasting like below
this.form.value as {username: string; rememberMe: boolean; password: string}
The above works but will it have to be typecast for all forms?
It is Partial
because some controls can be disabled (and potential undefined).
To get all values, use this.form.getRawValue()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With