Skip to main content

Add / Remove Multiple Input Fields Dynamically using Form Array in Angular Reactive Forms





Dynamically Create multiple input fields using angular

Using Angular Reactive Forms FormArray, we can easily add/remove multiple input fields (FormControl) or group of input fields (FormGroup) in a form.
In this tutorial, I will teach you how to create a group of addresses with both add and remove functionality using Angular Reactive Forms FormArray.





Steps to Create Dynamic Input Fields in Angular Reactive Forms

  • Import ReactiveFormsModule in your module
  • Declare a property called addressForm which is our FormGroup
  • Declare a property called addresses which is our FormArray
  • Use the FormBuilder Service to create our FormGroup model.
  • Write three methods addAddress , removeAddresscreateAddress

Import ReactiveFormsModule

In order to use FormGroupFormArray and FormControl we should import ReactiveFormsModule in our module (app.module.ts).
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    ReactiveFormsModule // import reactive forms module
  ]
});

Create FormGroup using Form Builder

Create a property called addressForm (whatever name you like) in your component.ts. Inject the FormBuilder service in your constructor.
FormBuilder is an angular service used to create FormGroups, FormControls, and FormArrays easily. By using FormBuilder.array method, you can create FormArray.

You may pass a function into the FormBuilder.array method to set the default value for it. The function should either return a FormControl or FormGroup.
In our case, we pass createAddress() inside the array method, by default a single address group will be created.
public addressForm: FormGroup;
  
constructor(private fb: FormBuilder) {
  this.addressForm = this.fb.group({
     addresses: this.fb.array([ this.createAddress() ])
  });
}

 createAddress(): FormGroup {
    return this.fb.group({
      address: '',
      street: '',
      city: '',
      country: ''
    });
 }

Dynamic FormGroups/FormControls in Component Template using FormArray

Create a form element and assign the addressForm as it’s formGroup
<form [formGroup]="addressForm" class="container mt-3">
   <!-- code form form array here -->
</form>

Add FormGroup/FormControls Dynamically in Angular Reactive Forms:

Create a button in your component.html, on its click invoke addAddress function as follows
<button type="button" class="btn btn-primary mb-2" (click)="addAddress()">Add Address</button>
In addAddress function, you should get the addresses formArray by accessing the get method of the FromGroup. Push the new FormGroup into the addresses formArray by invoking the createAddress function.
addAddress(): void {
    this.addresses = this.addressForm.get('addresses') as FormArray;
    this.addresses.push(this.createAddress());
}

List the Dynamically Created FormGroup using FormArray

In your component.html, you should loop over the FormArray using *ngFor directive. Create a getter to access the controls of the FormArray
// component.ts
get addressControls() {
  return this.addressForm.get('addresses')['controls'];
}
Loop over the form controls of FormArray, declare a local variable in the *ngFor to store the index in *ngFor=let address of addressControls; let i = index;
Assign the i to formGroupName dynamically, then create the necessary input fields and set the formControlName for it.
<section class="container border mb-4 p-3" formArrayName="addresses" 
        *ngFor="let address of addressControls; let i = index;">
        <div [formGroupName]="i">
          <div class="row">
            <div class="col-6">
                <h4>Address {{i + 1}}</h4>
            </div>
            <div class="col-6 text-right">
                <button type="button" class="btn btn-danger btn-sm" (click)="removeAddress(i)">Remove</button>
            </div>
          </div>
          <div class="row">
            <div class="col-6">
                <div class="form-group">
                    <label>Address</label>
                    <input type="text" class="form-control" formControlName="address" placeholder="St. Thomas Apartment"/>
                  </div>
            </div>
            <div class="col-6">
                <div class="form-group">
                    <label>Street</label>
                    <input type="text" class="form-control" formControlName="street" placeholder="South Street"/>
                  </div>
            </div>
          </div>
          
          <div class="row">
            <div class="col-6">
                <div class="form-group">
                    <label>City</label>
                    <input type="text" class="form-control" formControlName="city" placeholder="Mumbai"/>
                  </div>
            </div>
            <div class="col-6">
                <div class="form-group">
                    <label>Country</label>
                    <select class="form-control" formControlName="country" placeholder="India">
                      <option value="india">India</option>
                      <option value="usa">USA</option>
                      <option value="england">England</option>
                    </select>
                  </div>
            </div>
          </div>
        </div>
    
      </section>

Remove FormGroup/FormControl from FormArray in Angular Reactive Forms

Create a remove button inside the formGroupName div, on its click, invoke a method called removeAddress with the current index i.
<button type="button" class="btn btn-danger btn-sm" (click)="removeAddress(i)">Remove</button>
Inside your component.ts, create a method called removeAddress which will remove the form group from the form array using removeAt method.
removeAddress(i: number) {
   this.addresses.removeAt(i);
}

Conclusion:

I hope, This angular reactive forms tutorial helps you to understand how to add and remove multiple form controls or form groups using FormArray. If you have any doubts about implementing dynamic forms using the angular reactive forms module, make a comment below.

full code 


app.component.html
<form [formGroup]="addressForm" class="container mt-3" (ngSubmit)="logValue()">
  <div class="row justify-content-center">
    <div class="col-6">
        <button type="button" class="btn btn-primary mb-2" (click)="addAddress()">Add Address</button>
      <section class="container border mb-4 p-3" formArrayName="addresses" 
        *ngFor="let address of addressControls; let i = index;">
        <div [formGroupName]="i">
          <div class="row">
            <div class="col-6">
                <h4>Address {{i + 1}}</h4>
            </div>
            <div class="col-6 text-right">
                <button type="button" class="btn btn-danger btn-sm" (click)="removeAddress(i)">Remove</button>
            </div>
          </div>
          <div class="row">
            <div class="col-6">
                <div class="form-group">
                    <label>Address</label>
                    <input type="text" class="form-control" formControlName="address" placeholder="St. Thomas Apartment"/>
                  </div>
            </div>
            <div class="col-6">
                <div class="form-group">
                    <label>Street</label>
                    <input type="text" class="form-control" formControlName="street" placeholder="South Street"/>
                  </div>
            </div>
          </div>
          
          <div class="row">
            <div class="col-6">
                <div class="form-group">
                    <label>City</label>
                    <input type="text" class="form-control" formControlName="city" placeholder="Mumbai"/>
                  </div>
            </div>
            <div class="col-6">
                <div class="form-group">
                    <label>Country</label>
                    <select class="form-control" formControlName="country" placeholder="India">
                      <option value="india">India</option>
                      <option value="usa">USA</option>
                      <option value="england">England</option>
                    </select>
                  </div>
            </div>
          </div>
        </div>
    
      </section>

      <div class="text-right">
          <input type="submit" class="btn btn-success" value="Submit"/>
      </div>
      
    </div>
  </div>

</form>
/// app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  public addresses: FormArray;
  public addressForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.addressForm = this.fb.group({
      addresses: this.fb.array([ this.createAddress() ])
    });
  }

  ngOnInit() {

  }

  get addressControls() {
    return this.addressForm.get('addresses')['controls'];
  }

  createAddress(): FormGroup {
    return this.fb.group({
      address: '',
      street: '',
      city: '',
      country: ''
    });
  }

  addAddress(): void {
    this.addresses = this.addressForm.get('addresses') as FormArray;
    this.addresses.push(this.createAddress());
  }

  removeAddress(i: number) {
    this.addresses.removeAt(i);
  }

  logValue() {
    console.log(this.addresses.value);
  }
}
// app.component.scss$color-primary: rgba(67,66,93,255);
$color-text: #43425d;
$color-text-lite: rgba(#4d4f5c,.5);

.login-container {
    font-family: "Source Sans Pro";
    .sidebar {
        background-image: url(/assets/images/group_4.png), linear-gradient(-136.82353093203deg , rgba(36,35,72,255) 0%, rgba(90,85,170,255) 100%);
        background-size: cover;
        min-height: 100vh;
    }

    .title, a {
        color: $color-text;
    }

    .title {
        font-weight: bold;
        letter-spacing: 5px;
    }

    .tag {
        color: $color-text-lite
    }

    .btn-main {
        background: $color-primary;
    }

    .btn-main-outline {
        border: 1px solid $color-primary
    }

}
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    AppRoutingModule,
    BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }








Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...