-1

I am looking at the existing answer for question What is the difference between formControlName and FormControl?

and still struggle to fully understand when to use [formControl] over formControlName.

Am I correct to conclude [ based on @Paul Samsotha comment ] that when I create a control using FormBuilder similar to the

constructor(fb: FormBuilder) {
    this.myForm = fb.group({
        'fullname': ['', Validators.required],
        'gender': []
    });
}

Then I should use something like

<form [formGroup]="myForm">

  <label>
    First Name:
    <input type="text" formControlName="fullname">
  </label>

  <label>
    Last Name:
    <input type="text" formControlName="gender">
  </label>

</form>

and if I want to declare my form like the following (based on @Günter Zöchbauer ansewer):

constructor(fb: FormBuilder) {
    this.myForm = fb.group({
        'fullname': new FormControl('');
        'gender': new FormControl('')
    });
}

use the following syntax:

<form [formGroup]="myForm">

  <label>
    First Name:
    <input type="text" [formControl]="fullname">
  </label>

  <label>
    Last Name:
    <input type="text" [formControl]="gender">
  </label>

</form>

Is above correct? Also the same thing for [formGroup] and formGroupName: When would you use formGroupName over [formGroup]? I could not come up with an example for this one. Can you explain why one might use one over the other or what the recommended practice is (if any)?

MHOOS
  • 4,660
  • 10
  • 31
  • 65

1 Answers1

3

Basically, you use [formControl] or [formControlName] when your form is dynamic, when you have a fixed form you just use formControlName.

That happens because the [] structure in angular is one way binding, so it keeps watching for the value of any property you have in your component.

  • [formControl]="propertyInComponent"
  • [formControlName]="propertyInComponent"
  • formControlName="nameGivenByYou"
JuanF
  • 516
  • 3
  • 11
  • 1
    We can also use `[formControlName]` for dynamic forms. FormControl is used for standalone controls – yurzui Nov 16 '18 at 21:05