angular2 - 在父FormGroup的子组件中验证FormControlName

angular2 - 在父FormGroup的子组件中验证FormControlName

问题描述:

我有一个角度组件对应于生成不确定数量的子组件的表单/页面,每个表示一个单独的字段,我希望父组件的FormGroup验证包含在子组件中的字段。只有当我这样做,我得到一个错误:angular2 - 在父FormGroup的子组件中验证FormControlName

A FormControlName must have a corresponding FormGroup.

这里是我的父组件的模板代码:

<div class="form-group" [formGroup]="parentGroup"> 
    <table> 
    <tbody> 
     <tr *ngFor="let i of array"> 
     <child [property]="i" [options]="myForm.controls[i.id]"></child> 
     </tr> 
    </tbody> 
    </table> 
</div> 

的形式在组件文件此处定义。

private formAttrs: FormGroup; 

constructor(private _fb: FormBuilder) { } 

ngOnInit() { 
    this.myForm = this._fb.group({}); 
    for (var i = 0; i < this.array.length; i++) { 
    this.formAttrs.addControl(this.array[i].id, new FormControl(this.array[i].value, Validators.required)); 
    } 
} 

的子组件的模板代码是这样的:

<td class="prompt"> 
    {{i.label}} 
</td> 
<td class="required" width="1%"> 
    <span *ngIf="property.required">*</span> 
</td> 
<td> 
    <input type="text " class="form-control" [ngClass]="{error: !options.valid}" formControlName="property.id"> 
</td> 
<td> 

虽然没有什么定义,我按了多少孩子的部件我们添加添加FormControls在子组件类(除了“属性”和传递给“选项”的FormControl元素之外),我会认为父组件中的formGroup将能够与子组件中的formControlName匹配,但是相反,我得到错误:

EXCEPTION: Error in ./ChildComponent class ChildComponent - inline 
template:7:109 caused by: formControlName must be used with a parent 
formGroup directive. You'll want to add a formGroup directive and pass 
it an existing FormGroup instance (you can create one in your class). 

有没有办法解决这个错误?如果没有,有人可以提出这个问题的另一个解决方案吗?

在此先感谢。

这里的问题是,在一个表单组中不可能有多次具有相同的表单控件名称。

您需要为每个子组件声明一个自己的表单组,然后可以根据您的引用属性在父组件中迭代它。您可以使用指令组件方法FormGroupDirective.getControl(controlName)获得每个子窗体控件,如您在文档中所见:https://angular.io/docs/ts/latest/api/forms/index/FormGroupDirective-directive.html

+0

感谢您的回复。每一个子组件都有自己的“属性”成员,它具有唯一的“id”变量,所以formControlNames实际上是不同的。仍然可行? – user2850751

我遇到了一些在Plunker中实现此功能的事情。

首先,我们需要从父在我们formGroup传递给孩子,所以我们有一个FormGroup满足FormControls是一个FormGroup的一部分的模板引擎的执法:

child.component。 TS

@Input() parentGroup: FormGroup; 

child.component.html

<td [formGroup]="parentGroup"> 
<...> 
</td> 

然后我们还需要设置[formControl]评估property.id,否则它会查找名称“属性”。ID“:

<input type="text " class="form-control" [ngClass]="{error: !options.valid}" [formControl]="options"/> 

<input type="text " class="form-control" [ngClass]="{error: !options.valid}" formControlName="{{property.id}}"/> 

你的代码是用不同的变量绑定formGroup和使用formAttrs这是为了什么事情,所以我径自有点不清楚,他们昏倒一个你可以在Plunker中看到:http://plnkr.co/edit/3MRiO9bGNFAkN2HNN7wg?p=preview

+0

由于某种原因,与formControlName的数据绑定在我的情况下不起作用,但您的formControl示例完美地工作 – Anonymous