I am working on a project with dynamic checkboxes that retrieve data from an API. Below is the HTML file:
<form [formGroup]="form" (ngSubmit)="submit()">
<label formArrayName="summons" *ngFor="let order of form.controls.summons.controls; let i = index">
<input type="checkbox" [formControlName]="i">
{{summons[i].name}}
</label>
<div *ngIf="!form.valid">At least one order must be selected</div>
<br>
<button [disabled]="!form.valid">submit</button>
</form>
Here is the TypeScript file:
interface Item {
offenceType4: string;
permSpeed: string;
actSpeed: string;
itemAttributes: ItemAttributes;
offenceLoc: string;
itemNo: string;
summonDate: string;
distCode: string;
summonType: string;
hbtlOffndr: string;
itemAmount: number;
itemAttributesCount: number;
summonAmt: string;
offenceType1: string;
offenceCode1: string;
offenceType2: string;
offenceCode2: string;
offenceType3: string;
category: string;
offenceCode3: string;
offenceCode4: string;
respCode: string;
}
interface ItemAttributes {
attribute5: string;
attribute4: string;
attribute7: string;
attribute6: string;
attribute1: string;
attribute3: string;
attribute2: string;
}
interface RootObject {
items: Item[];
status: Status;
additionalProperties: AdditionalProperties;
metadata: Metadata;
}
export class InquiryResponseMultiselectComponent implements OnInit {
form: FormGroup;
summons = [];
data: any[];
constructor(
private formBuilder: FormBuilder,
private inquiryService: InquiryService
) {
this.form = this.formBuilder.group({
summons: new FormArray([], minSelectedCheckboxes(1)),
});
this.getSummon().subscribe(summons => {
this.summons = summons;
this.addCheckboxes();
});
}
ngOnInit() {
this.getSummon();
}
getSummon() {
return this.inquiryService.getData().pipe(map((item: RootObject) =>
item.items)) ;
}
addCheckboxes() {
this.summons.map(i => {
const control = new FormControl();
const formArray = this.form.controls.summons as FormArray;
formArray.push(control);
});
}
After fetching the response from the API to dynamically update my checkbox options, I encountered an error.
core.js:9110 ERROR TypeError: Cannot read property 'map' of undefined
If I don't perform mapping like this:
addCheckboxes() {
const control = new FormControl();
const formArray = this.form.controls.summons as FormArray;
formArray.push(control);
}
The default length of the formControl will be equal to 1, which is not desired. Any guidance on how to resolve this issue would be greatly appreciated.