Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 734
ibrahimxcool Avatar asked Jan 26 '26 23:01

ibrahimxcool


1 Answers

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)]],
    });
  }

}
like image 124
Rachid O Avatar answered Jan 29 '26 12:01

Rachid O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!