Search code examples
angularangular2-forms

Angular 2 - form group component


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>

The app-form-group component will look something like this:

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

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?


Solution

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