Home > Mobile >  Is there a way to make form values non nonNullable by default?
Is there a way to make form values non nonNullable by default?

Time:08-06

My form

  public loginForm = new FormGroup({
    username: new FormControl('', [Validators.required]),
    password: new FormControl('', [Validators.required, Validators.minLength(8)]),
  });

When getting the values of the form, this is its type

getRawValue(): {
  username: string | null;
  password: string | null;
}

I know I could do like this to suppress the null's

  public loginForm = new FormGroup({
    username: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    password: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.minLength(8)] }),
  });

But is there a way to make all the form control non nunllable by default?

If my form contains a lot of control, I would have to use nonNullable: true on all of it

CodePudding user response:

You can use the NonNullableFormBuilder, this way you remove the boilerplate associated with setting nonNullable

  const fb = new FormBuilder();
  const loginForm = fb.nonNullable.group({
    username: ['', [Validators.required]],
    password: ['', [Validators.required, Validators.minLength(8)]],
  });

another example with the injector:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular '   VERSION.major;
  loginForm: FormGroup
  
  constructor(private readonly fb: NonNullableFormBuilder) {
    this.loginForm = fb.group({
      username: ['', [Validators.required]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    });
  }

}
  • Related