Angular 2-表单组组件

问题描述:

我正在尝试构建一个数据驱动的表单,其输入来自另一个组件,例如:

I'm trying to build a data-driven form, with inputs coming from another component, like this:

<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
    <app-form-group [name]="name"></app-form-group>
    <app-form-group [name]="email"></app-form-group>
    <app-form-group [name]="other"></app-form-group>
</form>

app-form-group组件将如下所示:

<div class="form-group">
    <label class="col-md-2 control-label">{{Name}}</label>
    <div class="col-md-9">
  <input class="form-control" [name]="name" [formControlName]="formCtrlName">
</div>

问题是formControlName需要一个formGroup指令,因此出现此错误:

The problem is that formControlName needs a formGroupdirective, therefore I get this error:

Error : Error in ./FormGroupComponent class FormGroupComponent - inline template:3:58 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).

有什么办法可以解决这个问题?

Is there any way to get around this issue?

您应该在app-form-group组件中使用FormGroup [formGroup]="signupForm".您可以使用以下代码:

You should use your FormGroup [formGroup]="signupForm" in app-form-group Component.You can use this Code :

<div class="form-group" [formGroup]="signupForm">
  <label class="col-md-2 control-label">{{Name}}</label>
  <div class="col-md-9">
  <input class="form-control" [name]="name" [formControlName]="formCtrlName">
</div>