I want to create several select option inputs with the response of an API.
I have defined this form with a FormArray input.
this.myForm = this.fb.group({
name: [null, [Validators.required]],
details: this.fb.array([], Validators.required),
});
Then, the getter for the detail input as FormArray.
get detailsArr() {
return this.myForm.get('details') as FormArray;
}
I fetch data from a service and propagate the form values with the response. The response from the server for the details is something like this:
"details": [
{ "detailName": "detail 1", "detailValue": 2},
{ "detailName": "detail 2", "detailValue": 4},
{ "detailName": "detail 3", "detailValue": 5}
]
fetchData() {
this.dataService.getData().subscribe((res) => {
// Propagate details
this.detailsArr.push(this.fb.control(res.details));
// Propagate name
this.myForm.patchValue({
name: res.name,
});
});
}
The point is, I don't know how to set the value of the details array to the details response. With the push method I get an array inside an array, I mean:
"details": [
[
{ "detailName": "detail 1", "detailValue": 2}
]
]
The HTML is the following:
<form [formGroup]="myForm">
<div formArrayName="details">
<select *ngFor="let detail of detailsArr.controls; let i = index" [formGroupName]="i">
<option>{{ detail.detailName }}</option>
</select>
</div>
</form>
I tried with detailsArr.value in the for loop and seems to work, but don't know why.
I just have followed this Angular official documentation, but doesn't work. I don' know if this is the correct approach to solve this problem.