Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Validation angular2-验证父FormGroup的子组件中的FormControlName_Validation_Angular_Typescript_Nested - Fatal编程技术网

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

Validation angular2-验证父FormGroup的子组件中的FormControlName,validation,angular,typescript,nested,Validation,Angular,Typescript,Nested,我有一个与表单/页面相对应的角度组件,该表单/页面正在生成数量不确定的子组件,每个子组件表示一个单独的字段,我希望父组件的FormGroup验证子组件中包含的字段。只有当我这样做时,我才会得到一个错误: FormControlName必须具有相应的FormGroup 以下是我的父组件的模板代码: <div class="form-group" [formGroup]="parentGroup"> <table> <tbody> <

我有一个与表单/页面相对应的角度组件,该表单/页面正在生成数量不确定的子组件,每个子组件表示一个单独的字段,我希望父组件的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>
有没有办法避免这个错误?如果没有,有没有其他人可以建议解决这个问题的方法


提前感谢。

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


您需要为每个子组件声明自己的表单组,然后可以根据引用属性在父组件中对其进行迭代。您可以使用指令组件方法
FormGroupDirective.getControl(controlName)
获取每个子表单控件,正如您在文档中所看到的:

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

首先,我们需要将formGroup从父级传递给子级,这样我们就有了一个formGroup,以满足模板引擎对作为formGroup一部分的FormControl的强制执行:

子组件.ts

@Input() parentGroup: FormGroup;
child.component.html

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



您的代码使用了不同的变量绑定了
formGroup
,并使用了
formatrs
,这有点不清楚发生了什么,所以我继续将它们折叠为一个,您可以在Plunker中看到:

感谢您的回复。需要明确的是,每个子组件都有自己的“property”成员和唯一的“id”变量,因此FormControlName实际上是不同的。这仍然可行吗?在某种原因下,使用formControlName的数据绑定在我的案例中不起作用,但是您使用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).
@Input() parentGroup: FormGroup;
<td [formGroup]="parentGroup">
<...>
</td>
<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}}"/>