在Angular Reactive表单中用表单注册控制时出现问题 [英] Getting issue in registering contorl with form in Angular Reactive forms
问题描述
我正在研究Angular反应形式.最初,我在formgroup中有一个formarray.之后,我将formgroup推入formarray以动态添加表单控件.使用formControlName绑定这些控件时出现问题. 我收到此错误消息:找不到路径为"controlArray-> 0-> value"的控件
I am working on Angular Reactive forms. Initially I have an formarray in formgroup. afterwards I push formgroup into formarray to add form control dynamically. I am getting an issue when binding these control using formControlName. I am getting this Error: Cannot find control with path: 'controlArray -> 0 -> value'
这是我的组件类代码:
ngOnInit(){
this.reviewForm = this.fb.group({
'controlArray': new FormArray([])
});
this.showDefaultForm();
}
首先我要在FormsDb中获取数据,然后我要对其进行搜索以获取最后设置的默认表单.
First I am getting data in formsDb, then I am searching into it to get the last set default form.
showDefaultForm(){
for(let form of this.formService.formsDb){
if(form.formName==this.formService.defaultForm.formName){
this.selectedForm = form;
this.addForm();
}
}
}
addForm(){
for (let control of this.selectedForm.controlsArr){
(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group([{
controlType: control.controlType,
label: control.label,
value: ''
}]));
}
}
这是我的模板代码:
<form [formGroup]="reviewForm" (ngSubmit)="onSubmit()">
<div class="example-label">
<span class='block'>
<div formArrayName="controlArray">
<div *ngFor="let control of reviewForm.get('controlArray').controls; let i = index">
<div [formGroupName]="i">
<table>
<tr>
<span *ngIf="control.value">
<td>
<label>{{control.value.label}}</label>
</td>
<td><span *ngIf="control.value.controlType == 'select'">
<md-select placeholder="{{control.value.label}}" formControlName="value">
<md-option *ngFor="let option of control.value.options; let j=index"
[value]="option">{{control.value.options[j]}}</md-option>
</md-select>
</span></td>
<td> <span *ngIf="control.value.controlType == 'text'">
<md-form-field class="example-full-width">
<input mdInput type="text" placeholder="{{control.value.placeholder}}" formControlName="value" >
</md-form-field>
</span></td>
</span>
</tr>
</table>
</div>
</div>
</div>
</span>
</div>
</form>
我的模板代码中有问题吗,请帮忙.谢谢
Is there some issue in my template code, Please help. Thanks
推荐答案
我认为问题出在addForm函数中,当您推动该组时,无需使用方括号作为数组来创建它,诸如此类:>
i think the problem is in the addForm function, when you push the group, you no need create it with brackets as an array, something like that:
addForm(){
for (let control of this.selectedForm.controlsArr) {
(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
controlType: control.controlType,
label: control.label,
value: ''
}));
}
}
这篇关于在Angular Reactive表单中用表单注册控制时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!