Dynamically Add and Remove Form Fields in Angular

In this section, we are going to use Angular so that we can add and remove fields from the form dynamically. The following example will be very useful for us to learn this concept. We can do this in various versions of Angular like 678, and 9.

In our below example, we will create a form which will contain the name of product. It will also contain the Add Multiple Quantity options, where users can select more than one quantity with the price. In our angular application, we are going to create a dynamic form by using the formarray and formgroup. In order to add and remove fields, we will describe some steps, which are shown as follows:

Step 1:

This is the first step, and in this step, we will Import FormsModule.

src/app/app.module.ts:

import { NgModule } from '@angular/core';  

import { BrowserModule } from '@angular/platform-browser';  

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

     

import { AppComponent } from './app.component';  

     

@NgModule({  

  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],  

  declarations: [ AppComponent ],  

  bootstrap:    [ AppComponent ]  

})  

export class AppModule { }

Step 2:

In this step, we are going to Update TS file. For this, we will use the angular forms library to import the FormArray, FormControl, FormBuilder, and FormGroup.

src/app/app.component.ts

import { Component } from '@angular/core';  

import { FormGroup, FormControl, FormArray, FormBuilder } from '@angular/forms'  

    

@Component({  

  selector: 'my-app',  

  templateUrl: './app.component.html',  

  styleUrls: [ './app.component.css' ]  

})  

export class AppComponent  {  

  name = 'Angular';  

    

  productForm: FormGroup;  

     

  constructor(private fb:FormBuilder) {  

     

    this.productForm = this.fb.group({  

      name: '',  

      quantities: this.fb.array([]) ,  

    });  

  }  

    

  quantities() : FormArray {  

    return this.productForm.get("quantities") as FormArray  

  }  

     

  newQuantity(): FormGroup {  

    return this.fb.group({  

      qty: '',  

      price: '',  

    })  

  }  

     

  addQuantity() {  

    this.quantities().push(this.newQuantity());  

  }  

     

  removeQuantity(i:number) {  

    this.quantities().removeAt(i);  

  }  

     

  onSubmit() {  

    console.log(this.productForm.value);  

  }

Step 3:

In this step, we will create Template code. For this, we will use ngModel so that we can write code of html form. We will use the file app.component.html to add the below code. In our following form, we can also use the Bootstrap class.

src/app/app.component.html

<div class="container">  

    

  <h1> Dynamically Add New Input Fields in Angular </h1>  

    

  <form [formGroup]="productForm" (ngSubmit)="onSubmit()">  

      

    <p>  

      <label for="name">Product Name:</label>  

      <input type="text" id="name" name="name" formControlName="name" class="form-control">  

    </p>  

    

    <table class="table table-bordered" formArrayName="quantities">  

      <tr>  

        <th colspan="2">Add Multiple Quantity:</th>  

        <th width="150px"><button type="button" (click)="addQuantity()" class="btn btn-primary">Add More</button></th>  

      </tr>  

      <tr *ngFor="let quantity of quantities().controls; let i=index" [formGroupName]="i">  

        <td>  

            Quantity :  

            <input type="text" formControlName="qty" class="form-control">  

        </td>  

        <td>  

            Price:  

            <input type="text" formControlName="price" class="form-control">  

        </td>  

        <td>  

            <button (click)="removeQuantity(i)" class="btn btn-danger">Remove</button>  

        </td>  

      </tr>  

    </table>  

     

    <button type="submit" class="btn btn-success">Submit</button>  

      

  </form>  

      

  <br/>  

  {{this.productForm.value | json}}  

</div>

Now, the above application is ready to run. The following command will be used to run our above application.

ng serve  

After running this command, the following output will be generated:

Dynamically Add and Remove Form Fields in Angular

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *