首页 文章

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

提问于
浏览
3

我有一个角度组件对应一个表单/页面生成一个不确定数量的子组件,每个组件代表一个单独的字段,我希望父组件的FormGroup验证子组件中包含的字段 . 只有当我这样做时,我才会收到错误:

FormControlName必须具有相应的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>

表单在此处的组件文件中定义 . 我根据我们添加的子组件数量添加FormControls:

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>

虽然子组件类中没有定义任何内容(除了“属性”和为“选项”传递下来的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).

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

提前致谢 .

2 回答

  • 1

    我在Plunker中遇到了一些实现这一点的事情 .

    首先,我们需要将formGroup从父级传递给子级,因此我们有一个FormGroup来满足模板引擎对FormControls的一部分的执行:

    child.component.ts

    @Input() parentGroup: FormGroup;
    

    child.component.html

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

    然后我们还需要设置 [formControl] 或评估 property.id ,否则它会查找名称"property.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

  • 7

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

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

相关问题