Home > OS >  Angular Reactive form builder, can we set the form control value type?
Angular Reactive form builder, can we set the form control value type?

Time:08-19

Can we have typed reactive forms using Angular formbuilder? What I mean is setting the TValue on the formcontrol so we get the right type. E.g.

public myForm= this.fb.group({
    name: ['', [Validators.required, Validators.maxLength(142)]])
  });

If I want to apply it as a string to a variable. It does not work, as it can be null and undefined.

let name: string = this.myForm.get("name")?.value; // Not working!

With the "normal" FormControls I can tell it it's TValue type.

nameFormControl = new FormControl<string>('', {nonNullable: true});

Direct initialization is then possible:

let name: string= this.nameFormControl.value; // works

Can we have the same type safety in form builders?

CodePudding user response:

Yep, you can set easily non-nullable type in FormBuilder. It's even more strict to typed FormControl (cannot be null by default). Example:

    formBuilder.nonNullable.control<Type>(...);

group and array works either.

CodePudding user response:

Hi you can assign form control

public myForm = this.fb.group({
    name: new FormControl('', [
      Validators.required, 
      Validators.maxLength(142)
    ])
  });

then you can access:

let name: string = this.myForm.get("name")?.value;

Here is stackblitz for reference: Example

  • Related