I have an API that returns the data something like but the class is same but number of entries changes.
HTML file:
<div class="col-12 col-md-6" formArrayName="plans">
<div class="form-check"
*ngFor="let plan of plans; index as i" [formGroupName]="i">
<label class="form-check-label fw7 h5 mb0">
<input class="form-check-input" type="checkbox" formControlName="checkbox">
{{plan.planCode}}
</label>
<label *ngIf="plan.divisions.length > 0">
Divisions
<select class="form-control" formControlName="division">
<option *ngFor="let division of plan.divisions" [value]="division.divisionCode">
{{division.divisionName}}
</option>
</select>
</label>
</div>
</div>
TS file:
public plans: IPlan[] = new Array<Plan>();
public formControls: {
firstNameCtrl: FormControl,
plans: {
checkbox: FormControl;
division: FormControl;
}[]
};
ngOnInit() {
this.restSvc.getData("/api/plan/GetPlanDetails")
.subscribe((data => {
if (!data.errorMessage) {
this.plans = data;
} else {
this.errMsg = data.errorMessage;
}
}), error => {
this.errMsg = "We found some errors. Please review the form and make corrections.";
});
this.formControls = {
firstNameCtrl: this.fb.control('', Validators.required),
plans: this.plans.map((plan, i) => {
const divisionCode = plan.divisions.length > 0
? plan.divisions[0].divisionCode
: '';
return {
checkbox: this.fb.control(i === 0),
division: this.fb.control(divisionCode)
};
})
};
}
I am getting error
Cannot find control with path: 'plans -> 0'
where the plan is getting mapped before the subscribe completes. How to resolve this?
Sample data:
plans = [
{ planCode: "B3692", divisions: [] },
{ planCode: "B3693", divisions: [] },
{ planCode: "B67",
divisions: [
{ divisionCode: "2", divisionName: "Assisted Living " },
{ divisionCode: "1", divisionName: "LILC" }]
},
{ planCode: "B69",
divisions: [
{ divisionCode: "3", divisionName: "Four Seasons" },
{ divisionCode: "2", divisionName: "Lakeside" },
{ divisionCode: "1", divisionName: "Sunrise" } ]
}
];