Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 962
Alexandru Pufan Avatar asked Oct 06 '16 11:10

Alexandru Pufan


People also ask

What is difference between FormGroup and FormBuilder?

In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.

What is the difference between FormControl and formControlName?

[formControl] assigns a reference to the FormControl instance you created to the FormControlDirective . formControlName assigns a string for the forms module to look up the control by name. If you create variables for the controls, you also don't need the .

What is FormGroup and FormControl?

FormGroup is used with FormControl to track the value and validate the state of form control. In practice, FormGroup aggregates the values of each child FormControl into a single object, using each control name as the key.

How do I add a form control to a form group?

addControl() The addControl adds a control to the FormGroup at runtime. Find the method declaration. name: This is the control name to add to the FormGroup . control: This is the any implementation class of AbstractControl such as FormGroup , FormControl and FormArray .


1 Answers

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>
like image 94
Saeed Avatar answered Oct 18 '22 02:10

Saeed