I'm using ReactiveFormsModule
of Angular2 to create a component that contains a form. Here is my code:
foo.component.ts:
constructor(fb: FormBuilder) {
this.myForm = fb.group({
'fullname': ['', Validators.required],
'gender': []
});
}
foo.component.html (with [formControl]
):
<div class="fields">
<div class="field">
<label>Fullname*</label>
<input type="text" [formControl]="myForm.controls.fullname"/>
</div>
</div>
<div class="inline fields">
<label for="gender">Gender</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" checked="" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
<label>Male</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
<label>Female</label>
</div>
</div>
</div>
foo.component.html (with formControlName
):
<div class="fields">
<div class="field">
<label>Fullname*</label>
<input type="text" formControlName="fullname"/>
</div>
</div>
<div class="inline fields">
<label for="gender">Gender</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" checked="" tabindex="0" class="hidden" formControlName="gender">
<label>Male</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" tabindex="0" class="hidden" formControlName="gender">
<label>Female</label>
</div>
</div>
</div>
Both ways work. But i cannot figure out what is the difference between using [formControl]
and formControlName
.
I believe you missed an important point: [formGroup]
directive in the second example. formControlName
is used together with [formGroup]
to save your form multiple dot navigations. For example:
<div>
<input type="text" [formControl]="myForm.controls.firstName"/>
<input type="text" [formControl]="myForm.controls.lastName"/>
<input type="text" [formControl]="myForm.controls.email"/>
<input type="text" [formControl]="myForm.controls.title"/>
</div>
Is equivalent to:
<div [formGroup]="myForm">
<input type="text" formControlName="firstName"/>
<input type="text" formControlName="lastName"/>
<input type="text" formControlName="email"/>
<input type="text" formControlName="title"/>
</div>
Now imagine nested FormGroups
:)