Angular2: how to access a formControl value on a nested formBuilder form

Autorun picture Autorun · Sep 29, 2016 · Viewed 12.6k times · Source

How can I get the value of this.resFormGroup.patientName.lastname.value without using [ngModel]?

What are the purpose of name="resForm", [formGroup]="resFormGroup" and #resNgForm="ngForm" in the HTML <form> tag?

Do I need the template reference variable #resNgForm since I have the [formGroup]="resFormGroup"?

This is my component:

// FormBuilder
this.resFormGroup = this.formBuilder.group({
  patientName: this.formBuilder.group({
    firstname: ['', Validators.required],
    lastname: ['', Validators.required]
  }),
  address: this.formBuilder.group({
    street: [],
    zip: [],
    city: []
  })
});

This is my template:

<form name="resForm" [formGroup]="resFormGroup" (ngSubmit)="onSubmit()" #resNgForm="ngForm">
  <fieldset formGroupName="patientName">
      <legend>Name</legend>
  <label>Firstname:</label>
  <input type="text" formControlName="firstname" [(ngModel)]="myFirstName">

  <label>Lastname:</label>
  <input type="text" ***formControlName="lastname"***>
  </fieldset>

  <fieldset formGroupName="address">
      <legend>Address</legend>
      <label>Street:</label>
      <input type="text" formControlName="street">

      <label>Zip:</label>
      <input type="text" formControlName="zip">

      <label>City:</label>
      <input type="text" formControlName="city">
  </fieldset>

  <button type="submit" class="btn btn-primary" [disabled]="!resNgForm.valid">Submit</button>

My submit button:

 onSubmit() { 
   console.log("Submit button pressed [ngModel: " + this.myFirstName + "]    [Form: " + this.resFormGroup.controls["patientName"].dirty + "]"); 
 }

With [ngModel], I can get the first name; I can also access the dirty attribute of the formGroup's patientName.

Answer

Autorun picture Autorun · Oct 1, 2016

Based on this tutorial about dynamic form, they used a very simple way to show the values of the whole form without [ngModel].

How to get the formBuilder form values? The answer is 'this.myForm.value'.

Example code

For example:

onSubmit(model: ResCrud) {  
    console.log("Nested Control: " + JSON.stringify(this.resFormGroup.value));
}

How it looks in the web console

angular formbuilder nested value example