【发布时间】:2021-05-02 06:43:19
【问题描述】:
我有一个子组件,其中有两个FormGroup。一个是简单的 FormControl,另一个是 FormArray。我遵循了这个stackblitz 示例以及与FormArray 相关的许多其他示例,但仍然不知道为什么它不起作用。
自定义条件.ts
@Input() parentForm: FormGroup;
customConditions: FormGroup
ngOnInit() {
this.initForm()
}
initForm(){
this.customConditions = this.fb.group({
custom: this.fb.array([])
});
this.getCustomArray.push(this.getCustomConditionController())
this.parentForm.addControl("CustomConditions", this.customConditions);
}
get getCustomArray(): FormArray {
return <FormArray>this.customConditions.get("custom")
}
getCustomConditionController(): FormGroup {
return this.fb.group({
ConditionArabic: this.fb.control(""),
ConditionEnglish: this.fb.control("")
});
}
addCustomConditions() {
this.getCustomArray.push(this.getCustomConditionController())
}
removeCustomConditions(i: number) {
this.getCustomArray.removeAt(i)
}
isLastRow(rowIndex: any) {
return this.customConditions.controls.length == rowIndex + 1
}
自定义条件.html
<div class="row" [formGroup]="customConditions">
<ng-container formArrayName="custom">
<div class="col-12" *ngFor="let fg of getCustomArray.controls; let i = index">
<div class="row mt-3 mb-3" [formGroupName]='fg'>
<div class="col-4">
<div class="form-group">
<label for="ConditionEnglish{{i}}" class="control-label">Condition English</label>
<input
type="text"
class="form-control"
tabindex="{{i+1}}"
id="ConditionEnglish{{i}}"
formControlName="ConditionEnglish"
autocomplete="off" />
</div>
</div>
<div class="col-4">
<div class="form-group">
<label for="ConditionArabic{{i}}" class="control-label">Condition Arabic</label>
<input
type="text"
name="ConditionArabic"
class="form-control"
tabindex="{{i+1}}"
id="ConditionArabic{{i}}"
formControlName="ConditionArabic"
autocomplete="off" />
</div>
</div>
<div class="col-4">
<span class="file-add" *ngIf="i > 0">
<a (click)="removeCustomConditions(i)"><i class="fal fa-trash-alt"></i></a>
</span>
<span class="file-add" *ngIf="isLastRow(i)">
<a (click)="addCustomConditions()"><i class="fal fa-plus-circle"></i></a>
</span>
</div>
</div>
</div>
</ng-container>
</div>
错误获取:
ERROR Error: Cannot find control with path: 'custom -> [object Object]' 也 this.customConditions.get("custom") 在组件加载后返回空数组,这就是为什么 getCustomArray.controls 为空所以 html 不呈现。
我在这里做错了什么?
【问题讨论】:
-
试试formgroupname = i,而不是form中的fg
-
@Eyeslandic 谢谢!我怎么看不到这个。
标签: angular formarray formgroups