角度 找不到路径:'childrenFormArray -> [object Object] -> gender'的控件



我正在做一个有角度的项目,我正试图用反应形式动态添加多个不同年龄和性别的孩子。虽然正在添加表单,但其中的删除部分不起作用。每次我尝试添加时,都会不断弹出一个错误

Cannot find control with name: 'childrenFormArray'

这是我的ts代码

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()
}

}

这是我打印表单的html代码

<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>

您需要确保您的html与您的表单匹配,例如您的表单具有结构

childrenFormGroup: FormGroup
childrenFormArray : FormArray
[0] : FormGroup
gender: FormControl
age: FormControl
[1] : FormGroup
gender: FormControl
age: FormControl

现在我们可以回到您的表格,并尝试满足以上

<form [formGroup]='childrenFormGroup'>
<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>
<ng-container formArrayName="childrenFormArray">
<div *ngFor="let item of childrenFormGroup.get('childrenFormArray')['controls']; let i = index;" [formGroupName]='i'>
<div>
<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>

注意这两行

<ng-container formArrayName="childrenFormArray">
...
[formGroupName]='i'

相关内容

最新更新