M. Lee
M. Lee

Reputation: 127

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

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?

Upvotes: 1

Views: 7250

Answers (2)

Sonu Sindhu
Sonu Sindhu

Reputation: 1792

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

Upvotes: 0

Anton Marinenko
Anton Marinenko

Reputation: 2982

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.

Upvotes: 3

Related Questions