To get the nested form group value in Angular Reactive Form, you can use the get()
method to retrieve the form control within the nested form group and then use FormControl.value
property to get the value of any nested form controls you want.
For example, let’s say we have a form group with four form controls, firstName
, lastName
, city
and postalCode
.
The city
and postalCode
form controls are nested inside the address
form group.
We want to get the value of the address
form group which is nested inside the main form group as soon as you click the submit button.
<div class="container"> <form [formGroup]="userForm"> <div> <input type="text" formControlName="firstName"> <label> First Name</label> </div> <div> <input type="text" formControlName="lastName"> <label> Last Name</label> </div> <!-- Add the Nested Form Group --> <div formGroupName="address"> <div> <input type="text" formControlName="city"> <label> City</label> </div> <div> <input type="text" formControlName="postalCode"> <label> Postal Code</label> </div> </div> <button type="submit" (click)="submit()">Submit</button> </form> </div>
Add the code into the ts file:
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { userForm: FormGroup; constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ firstName: ['', Validators.required], lastName: ['', Validators.required], address: this.fb.group({ city: ['', Validators.required], postalCode: [''], }) }); } ngOnInit(): void { } submit() { // Get the nested form group const address = this.userForm.get('address'); // Get the nested form group value const addressValue = address?.value; console.log(addressValue); } }
Output:
As you can see from the above output, the value of the nested form group address
is printed to the console as soon as you click the submit button.
You can get the value of each nested form control by calling the FormControl.get()
method on the nested form group and then using the value
property to access its value.
See this example,
submit() { // Get the nested form group const address = this.userForm.get('address'); // Get the nested form group value const addressValue = address?.value; // Get city and postal code const city = address?.get('city')?.value const postalCode = address?.get('postalCode')?.value; // Print values console.log(city); console.log(postalCode); }
That’s all for this article. Thanks for reading!