Issue
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?
Solution
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.
Answered By - Anton Marinenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.