I have a typed FormGroup based on the following interface. Note that proId is optional:
interface FormData {
name: FormControl<string>;
age: FormControl<number | null>;
active: FormControl<boolean>;
proId?: FormControl<number>;
}
constructor(private formBuilder: NonNullableFormBuilder) {}
form: FormGroup<FormData> = this.formBuilder.group({
name: '', // will be initialized in ngOnInit when @Input() can be accessed
age: null as number | null, // will be initialized in ngOnInit when @Input() can be accessed
active: false as boolean,
proId: 0
});
But how to initialize the proId FormControl correctly? With my solution above I get the following error:
TS2322: Type 'FormGroup<{ name: FormControl<string>; age: FormControl<number>; active:
FormControl<boolean>; proId: FormControl<number>; }>' is not assignable to type
'FormGroup<FormData2>'. Type 'FormControl<number> | undefined' is not assignable to type
'FormControl<number>'. Type 'undefined' is not assignable to type 'FormControl<number>'.
And a second question:
Is it the correct way to initialize the following two fields like this:
age: null as number | null
active: false as boolean
Because if I only use
active: false
I get the following error:
Type 'FormControl<boolean>' is not assignable to type 'FormControl<false>'. Type 'boolean'
is not assignable to type 'false'.
In typed form when we use FormBuilder, We need to define formControl to each key explicitly
Try this:
form:FormGroup<FormData> = this.formBuilder.group<FormData>({
name: this.formBuilder.nonNullable.control(''),
age: this.formBuilder.control(null),
active: this.formBuilder.control(false),
proId: this.formBuilder.control(0)
});
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With