What is the difference between formControlName and FormControl?
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
:)
[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 .
as mentioned by Harry, but I'd also suggest to use [formGroup]
instead because with more complicated forms this can become messy.
constructor(fb: FormBuilder) {
this.fullName = new FormControl('', Validators.required);
this.gender = new FormControl('');
this.myForm = fb.group({
'fullname': this.fullName,
'gender': this.gender
});
}