角度2 - 形式组成分

时间:2016-10-06 11:45:09

标签: angular angular2-forms

我试图构建一个数据驱动的表单,输入来自另一个组件,如下所示:

<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指令,因此我收到此错误:

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).

有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:5)

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

<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>

答案 1 :(得分:4)

您可以使用@Input属性来获取子组件的引用:

应用外形group.ts:

@Input('group')
public signupForm: FormGroup;

app.html:

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

应用外形group.html:

<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>

有关详细信息,请查看本教程:https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2