From data that I recive from API I want to create a reactive form. I have a formparent and multiple childforms. The data that I want to display in form looks like this:
data{
"extraInformation": false
"cars": [
{
"Id": 48,
"Period": {
"Start": null,
"End": null },
"Rentalstats": null,
"Reason": null
}
]
}
How do I achieve this? So far this is what I have done:
this.form = this.formBuilder.group({
extraInformation: [this.data.ExtraInformation, [Validators.required]],
cars: this.fb.array([this.addDetailFormGroup()]),
});
addDetailFormGroup() {
this.form = new FormGroup({
Reason: new FormControl(this.data?.cars?.Reason, Validators.required),
Rentalstats: new FormControl(this.data?.cars?.Rentalstats, Validators.required),
Period: new FormGroup([this.initListFormGroup()]),
});
initListFormGroup() {
return new FormGroup({
Start: new FormControl(this.data?.cars?.Period?.Start, Validators.required),
End: new FormControl(this.data?.cars?.Period?.End, Validators.required),
});
}
But it dosent work because I get "Cannot read properties of undefined (reading 'Start')..
I would really appreciate it if someone could help
Would say that your code is not compilable as there are a few errors:
You are trying to re-assign the
FormGroupinstance with the form controls:Reason,Rentalstats, andPeriodthat overwrite the originalFormGroupwith the form controls:extraInformationandcarsarray.From the attached data,
this.data?.carsis an array, you can't directly accessReasonand other fields, but you need to iterate each element of thecarsarray, createFormGroupfor each element and adding it into thecarsFormArray.Period: new FormGroup([this.initListFormGroup()]),This is not the proper way to assign theFormGroupinstance toPeriodFormGroup. Your current code is trying to assign the value asFormGroupto aFormGroupcontrol.Incorrect way to declare
initListFormGroupmethod. You should declare the method outside ofaddDetailFormGroupmethod.The naming of the methods to create
FormGroupis unclear/not meaningful, you should name it something likeinitCarFormArrayandinitPeriodFormGroupfor better readability.The component code to create the
formand its nestedFormArrayand `FormGroup(s) should look as below:For the HTML to generate the
form:Demo @ StackBlitz