DEV Community

Cover image for How to Handle Dynamic Form fields in Reactive forms in Angular
Manoj Prasanna  πŸš€
Manoj Prasanna πŸš€

Posted on • Updated on

How to Handle Dynamic Form fields in Reactive forms in Angular

In this article, I will explore the process of handling dynamic forms in the Angular framework using Reactive Forms. Dynamic forms allow us to dynamically generate form fields based on user input or other conditions. By leveraging the power of Reactive Forms, we can easily handle dynamic form interactions in Angular. Let's dive into the step-by-step process of creating and managing dynamic forms in Angular.

Reactive Forms

First we will explain what is reactive form in angular,
Reactive forms are build around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously.In Angular their have two type of forms ,

  1. Template-driven forms

  2. Reactive Forms

Related to above form type the suitable to create dynamic form from Reactive forms, Lets started with building simple sample application.

Scenario

Step-01 : Setting up the Angular project

First, Let's create a new Angular project using the Angular CLI.
Open your command prompt(terminal) and run the following command.

ng new dynamic-forms-demo
Enter fullscreen mode Exit fullscreen mode

Step-02 : Create the new component

Create a new component for the dynamic form

ng generate component dynamic-form
Enter fullscreen mode Exit fullscreen mode

another way

ng g c dynamic-form
Enter fullscreen mode Exit fullscreen mode

Now you will create a component name call dynamic-form under the "src" folder

Image description

Step 3: Import the Required Modules

In order to work with Reactive Forms, we need to import the ReactiveFormsModule from @angular/forms module. Open the app.module.ts file in your project and add the following import statement:

import { ReactiveFormsModule } from '@angular/forms';
Enter fullscreen mode Exit fullscreen mode

Then include the ReactiveFormsModule to the imports sections

@NgModule({
  declarations: [
    // Other declarations
  ],
  imports: [
    // Other imports
    ReactiveFormsModule
  ],
  providers: [
    // Other providers
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

Step 4: Set Up the Reactive Form

doing inside of the dynamic-form.component.ts

Import the FormArray, FormBuilder, FormGroup to the dynamic-form component

import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
Enter fullscreen mode Exit fullscreen mode

Then,inside the class define the dynamicFormGroup

export class DynamicFormComponent implements OnInit {

  dynamicFormGroup!: FormGroup;  //defined the dynamicFormGroup

  constructor() { }

  ngOnInit() {

  }

}
Enter fullscreen mode Exit fullscreen mode

In the component's constructor, initialize the form group and form array

export class DynamicFormComponent implements OnInit {

  dynamicFormGroup!: FormGroup;

  constructor(private formBuilder : FormBuilder) { }

  ngOnInit() {
    this.dynamicFormGroup = this.formBuilder.group({
          Address: new FormArray([])
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Then create the dynamic fields for the Address

get createItem(): FormGroup {
    return this.formBuilder.group({
      streetAddress: [],
      city:[],
      state:[]
    })
  }
Enter fullscreen mode Exit fullscreen mode

Now we need to add the createItem method fields for the Address group, The createItem method creates a new instance of the FormGroup for the Address group, with the corresponding form control fields (streetAddress, city, state,) and their initial values set to an empty string.

 ngOnInit() {
    this.dynamicFormGroup = this.formBuilder.group({
      Address: new FormArray([this.createItem]),
    });
  }
Enter fullscreen mode Exit fullscreen mode

Step 5: Build the Dynamic Form Template

Now, let's construct the template for our dynamic form in the dynamic-form.component.html file.

 <div>
    <form [formGroup]="dynamicFormGroup" (ngSubmit)="onSubmit()">
        <div class="form-row" *ngFor="let fields of AddressInfo.controls; let i = index" >
            <div class="form-group col-md-3" >
                <label for="password"><b>Street Address</b></label>
                <input type="text" class="form-control" placeholder="Street Address" name="SA" formControlName="streetAddress" />
              </div>
              <div class="form-group col-md-3" >
                <label for="password"><b>City</b></label>
                <input type="text" class="form-control" placeholder="City" name="city" formControlName="city" />
              </div>
              <div class="form-group col-md-3" >
                <label for="password"><b>State</b></label>
                <input type="text" class="form-control" placeholder="State" name="state" formControlName="state" />
              </div>
        </div>
        <br/>
     <button type="submit"  class="btn btn-primary">Submit</button>
    </form>
    <br/>
    <button type = "button" class="btn btn-primary" (click)="addNewAddress()" >Add New Address</button>
</div>    

<h4>OUTPUT</h4>
<div>{{output}}</div>
Enter fullscreen mode Exit fullscreen mode

Step 7: Display and Interact with the Dynamic Form

In the template, add a button to trigger the addition of form fields dynamically:

<button type = "button" class="btn btn-primary" (click)="addNewAddress()" >Add New Address</button>
Enter fullscreen mode Exit fullscreen mode

Additionally, you can bind the form array's controls to display the dynamic form fields

<div class="form-row" *ngFor="let fields of AddressInfo.controls; let i = index" >
<!-- Display form fields dynamically -->
</div>
Enter fullscreen mode Exit fullscreen mode

Step 8: Handle Form Submission

To handle the form submission, create a method in the component:

onSubmit() {
//logic implementation
this.output = this.dynamicFormGroup.controls['address'].value;
    console.log(this.output);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:
By following these step-by-step instructions, you have learned how to create dynamic forms in Angular using Reactive Forms. Leveraging the power of Reactive Forms and Angular's capabilities, you can now handle and manage dynamic forms seamlessly. This knowledge opens up new possibilities for building interactive and user-friendly applications in Angular. Happy coding!
Here is the Example Solution :Angular Dynamic Forms handling reactive forms

That’s It!
Of course you probably want to see this in action. Here’s a working demo for you to fork or play with:

Thanks for reading the whole story ❀

PC : https://morioh.com/p/3cbcfff8086a

Top comments (0)