I'm currently working on an angular project and facing a challenge in adding multiple children with their age and gender dynamically using reactive forms. Although I can add the form, I am having trouble with the delete functionality as it keeps throwing an error message:
Cannot find control with name: 'childrenFormArray'
Here is my TypeScript code:
ngOnInit(): void {
this.childrenFormGroup= this.formBuilder.group({
childrenFormArray: this.formBuilder.array([ this.createItem() ])
});
}
createItem(): FormGroup {
return this.formBuilder.group({
gender: new FormControl(''),
age: new FormControl(''),
});
}
addItem(): void {
if(this.childrenFormGroup.get('childrenFormArray'['controls'].length<this.numberOfChildren) {
this.childrenFormArray = this.childrenFormGroup.get('childrenFormArray') as FormArray;
this.childrenFormArray.push(this.createItem());
this.addItem();
}
else if(this.childrenFormGroup.get('childrenFormArray'['controls']>this.numberOfChildren) {
this.childrenFormArray = this.childrenFormGroup.get('childrenFormArray') as FormArray;
this.childrenFormArray.removeAt(this.childrenFormArray.length-1);
this.addItem()
}
}
This is my HTML code to display the form:
<div class="col-12 ">
<fieldset class="form-group ">
<label class="form-label " for="numberOfChildren">Number Of Children</label>
<input type="number" class="form-control " id="numberOfChildren" [ngModelOptions]="{standalone: true}" placeholder="Enter number of children" (input)="addItem()" [(ngModel)]="numberOfChildren" required>
<div formArrayName="childrenFormArray" *ngFor="let item of childrenFormGroup.get('childrenFormArray')['controls']; let i = index;">
<div [formGroupName]="childrenFormGroup.get('childrenFormArray')['controls'][i]">
<select formControlName="gender" >
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Others</option>
</select>
<input type="number" formControlName="age" placeholder="Age of Child">
</div>