Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indicate that all fields are not optional in typed form group

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?

like image 269
Owen Kelvin Avatar asked Sep 12 '25 03:09

Owen Kelvin


1 Answers

It is Partial because some controls can be disabled (and potential undefined).

To get all values, use this.form.getRawValue().

like image 102
Eugene Avatar answered Sep 13 '25 17:09

Eugene