At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

Building Dynamic Nested Reactive form In Angular

  • By Preetha Ravi
  • February 13, 2020
  • 3020 Views

Most of the applications that are built today are just forms, there are numerous forms, and even some of those are dynamic. The structure of the form changes depending on the user. They contain a lot of data. Today, we will take a look into nested reactive forms in Angular 4.
Let’s go!

Reactive Forms

Angular reactive forms
One of the primary reasons why we are using Reactive form is due to the synchronous property of the form whereas the template-driven forms are not synchronous. Reactive forms are driven through the “Form Control” where the value will be in our control.
The value will be updated concurrently once we are done with the changes in form as it would be easy for unit testing. Another advantage of using a Reactive form is that we can easily create tree structures and validations without any hassles.

Nested Forms

Nested Forms will allow us to create the array of objects for a single field and this hierarchy goes on. (i.e) A single object can have a number of objects inside of it, and we can achieve it in Reactive forms through the concept of “Form Array”.
For example, In Nested form, if you want to create a user profile there you can add multiple addresses and inside of that address, we can add multiple phone numbers similarly the list goes on.

For example,
{
"name": 'abc',
"addressess": [{
"street": 'nehru nagar',
"phone number": [
{
number1: 9845612378
},
{
number2: 1589635015
}]
},
{
"street": 'gandhi nagar',
"phone number": [
{
number1:7412563474
},
{
number2:1578963248
}]
}]
}

How to Build the Nested Reactive Form in Angular?

These are the 3 steps required to create Nested Reactive Form,
Step 1: create a new application in angular using the command.

“ng new new-app.”

Step 2: Import the forms module and reactive forms module in the app.module.ts file.
Step 3: Three fundamental blocks are used to build a reactive form in ngoninit. There are

  1. formcontrol
  2. formgroup
  3. formarray

Now, Let’s look into these 3 Blocks.

1. FormGroup

FormGroup is the basic block which is formed with various elements of form control and form array. The name of the form control elements will be considered as the key in the formgroup. First, we want to initialize the form name as a formgroup. If we add validation to the child components, once the child element validation gets failed, then the form group validation also would get fail.

2. FormArray

Form array will contain the array of formcontrol objects. It can have an array of objects. Same as form group, if one validation of form control fails, the entire form array validation would get fail. Plus, Some basic built-in methods of formarray are,

  • at(i: index) – get the formcontrol of the given index
  • push(control)  – push the controls at the end of the array
  • insert(i: index, control)  – Add the control at the given index
  • remove at(i: index)  – Will Remove the control at the given index

3. FormControl

The primary use of formcontrol is, We could easily track the changes that occur in the form. At first, we can initialize the value of the form control. Now, we can add the validation in the form control which is used to validate the particular field. Additionally, We can also give options for the form control. Usually, the form control would get updated on the blur event.
An example syntax for the formcontrol is shown below,

const c = new FormControl(‘’, Validators.required,{ updateOn: ‘blur’}

Related: Angular 4 Template Driven Forms: Building and Validating Forms

FormBuilder

To give easy syntax. Formbuilder will act as a medium for initializing form array, form control, form group. And, it can be done using the inbuilt methods of the form builder.
To use the formbuilder , we want to import formbuilder from the angular forms.
Methods used in FormBuilder are,

  • group() will return a new formgroup
  • control() will return a new formcontrol
  • array() will return a new formarray

In the Below code, I have given an example for initializing the nested reactive forms. To ensure your reactive form is user-friendly, you can able to add or remove multiple addresses, and also each address can have multiple mobile numbers.
The code snippet for initializing form group, form array is given below,

ngOnInit() {
this.myForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.minLength(5)]],
addresses: this.formBuilder.array([
this.initAddress(),
])
});
}
initAddress() {
return this.formBuilder.group({
street: ['', Validators.required],
postcode: [''],
phonenumber: this.formBuilder.array([
this.initNumber()
])
});
}
initNumber() {
return this.formBuilder.group({
number: ['', Validators.required]
})
}

The HTML code for adding Address, Number, removing address and number is given below,

<div formArrayName="addresses">
<div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default">
<div class="panel-heading ">
<span>Address {{i + 1}}</span>
<a *ngIf="myForm.controls.addresses.controls.length > 1" (click)="removeAddress(i)" style="cursor: default">
X
</a>
</div>
<div class="panel-body" [formGroupName]="i" class="col-md-12 border">
<div class="row">
<div class="form-group col-md-6">
<label>street</label>
<input type="text" class="form-control" formControlName="street">
</div>
<div class="form-group col-md-6">
<label>postcode</label>
<input type="text" class="form-control" formControlName="postcode">
</div>
</div>
<div class="row">
<div formArrayName="phonenumber" *ngFor="let number of myForm.controls.addresses.controls[i].controls.phonenumber.controls; let j=index" class="col-md-6">
<div [formGroupName]="j" >
<div class="form-group" style="padding-right:0px">
<label>Number</label>
<a *ngIf="address.controls.phonenumber.controls.length > 1" (click)="removeNumber(address, j)" style="cursor: default">X</a>
<input type="text" class="form-control" placeholder="Enter Number" formControlName="number">
</div>
</div>
<a class="pull-right" *ngIf="j == address.controls.phonenumber.controls.length-1" (click)="addNumber(address)" >AddNumber</a>
</div>
</div>
</div>
</div>
</div>

I have added the live preview for building nested reactive form as you can see it using this link.
I hope you find this building useful to build nested reactive forms for your Angular applications. Throw your doubts, we are happy to solve it for you. Like what you’re reading? then get our exclusive updates and blogs on Angular by subscribing to the newsletter.
If you are looking for Angular developers for your project? Hire Angular developer from Agira Technologies to build the best web-apps at affordable rates. Our dedicated Angular developers are well-versed with all the updates and ensure top-notch web application development to meet your business requirements. For any queries reach us via info@agiratech.com

Turn your vision to magnificent reality With
Our Web and Mobile Solutions