Skip to main content

Add / Remove Multiple Input Fields Dynamically in Template Driven Form – Angular




Dynamically Create multiple input fields using angular

In this tutorial, I will guide you on how to dynamically create multiple input fields using template driven forms in Angular. We are going to develop an addresses list. The user can add/remove multiple address list which contains the address, street, city, and country input fields.
By using Angular *ngFor the built-in directive, We can create dynamic input fields by looping through an array. We can also set the [(ngModel)] of the input fields dynamically to retrieve the value of the fields.



dynamically create multiple inputs using angular

Steps to Create Dynamic Input Fields in Template Driven Forms

  • Declare an empty array in your component.
  • Create methods for adding and removing the values in the array.
  • Use *ngFor directive to loop over the array to render multiple input fields
  • Dynamically set the [(ngModel)] and name attribute for the input fields using the array of object and index.

Create Multiple Input Fields Dynamically in Angular Template Driven Forms

In your component.ts file, declare an empty array. I am creating an empty array called addresseswhich has an empty object to render a single input by default.
 public addresses: any[] = [{
    address: '',
    street: '',
    city: '',
    country: ''
  }];
In your component.html, you should create a <form> inside the form you should loop over the addresses array using *ngFor directive.
<form #addressForm="ngForm" class="container mt-3" (ngSubmit)="logValue()">
  <!-- some code here - see full code at the end of this tutorial -->
   <section *ngFor="let address of addresses; let i = index;">
      <!-- input fields inside the *ngFor -->
         <label>Address</label>
         <input type="text" [(ngModel)]="address.address"
           name="address_{{i}}"/>
         <label>Street</label>
         <input type="text" [(ngModel)]="address.street"
           name="street_{{i}}"/>
         <label>City</label>
         <input type="text" [(ngModel)]="address.city"
           name="city_{{i}}"/>
         <label>Country</label>
         <select [(ngModel)]="address.country" name="country_{{i}}" placeholder="India">
               <option value="india">India</option>
               <option value="usa">USA</option>
                <option value="england">England</option>
         </select>
   </section>
 </form>

How to use *ngFor to loop over the array

The built-in *ngFor directive is used to render elements in the DOM by looping over an array using the following syntax
*ngFor="let address of addresses; let i = index"
The address is the current item of the addresses array. i is the current index of the array.

How to set ngModel dynamically inside the *ngFor – Template Driven Forms

The addresses is an array of object. we can use set the ngModel dynamically as [(ngModel)]="address.street" because address is the current item of the loop.
But still, there’s a problem in it, we should define a name attribute for our input fields, the nameshould be dynamic. we can make use of the i (index) inside the *ngFor loop. Ex: name="street_{{i}}
<input name="street_{{i}}" type="text">
After that, create two methods to add and remove address object in the addresses array.

Add Input Field – Angular Template Driven Forms

Create a button called “Add Address” in your componen.html, on it’s click event invokes the addAddress method.
<form> 
<!-- Add button -->
 <button type="button" (click)="addAddress()">Add Address</button> 
<!-- ngFor code --> 
</form>
The addAddress method pushes a new empty address object into the addresses array.
addAddress() {
    this.addresses.push({
      address: '',
      street: '',
      city: '',
      country: ''
    });
  }

Remove Input Field – Angular Template Driven Forms

Create a button called “Remove” inside the *ngFor in your component.html, on its click invoke the removeAddress method with the i (index) value as its parameter to remove the addressobject.
<section class="container border mb-4 p-3" *ngFor="let address of addresses; let i = index;">

     <button type="button" class="btn btn-danger btn-sm" (click)="removeAddress(i)">Remove</button>

</section>
removeAddress(i: number) {
    this.addresses.splice(i, 1);
  }

How to get the value of the dynamically created input fields

You can easily get the value of the dynamically created inputs by accessing the addresses array which has objects acting as [(ngModel)] for all the inputs. You can console.log(this.addresses) on form submit (ngSubmit).

Solve Index Issue in *ngFor

Inside the *ngFor, we are using the index of the loop to add unique name and ngModel for each input element. If we remove any element in between the rendered list, the index property will be reassigned which results in some weird issues like data replaced from one input to another one etc.
To solve this issue, you can add a unique property while adding new address. Modify your addAddress component like below:
addAddress() {
    this.addresses.push({
      id: this.addresses.length + 1,
      address: '',
      street: '',
      city: '',
      country: ''
    });
  }
In the above code, we are adding a new property called id which holds the value of the incremented addresses array length.
<form #addressForm="ngForm" class="container mt-3" (ngSubmit)="logValue()">
  <!-- some code here - see full code at the end of this tutorial -->
   <section *ngFor="let address of addresses; let i = index;">
      <!-- input fields inside the *ngFor -->
         <label>Address</label>
         <input type="text" [(ngModel)]="address.address"
           name="address_{{address.id}}"/>
         <label>Street</label>
         <input type="text" [(ngModel)]="address.street"
           name="street_{{address.id}}"/>
         <label>City</label>
         <input type="text" [(ngModel)]="address.city"
           name="city_{{address.id}}"/>
         <label>Country</label>
         <select [(ngModel)]="address.country" name="country_{{address.id}}" placeholder="India">
               <option value="india">India</option>
               <option value="usa">USA</option>
                <option value="england">England</option>
         </select>
   </section>
 </form>
Replace the i value in the input elements with address.id that is our unique id.

Dynamic Multiple Input Fields in Angular Full Code

The below code is a working example of dynamic inputs in Angular.

FULL CODE EXAMPLE FOR MULTIPLE INPUT FIELDS IN TEMPLATE DRIVEN FORM

// app.component.html
<form #addressForm="ngForm" 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" *ngFor="let address of addresses; let i = index;">
        <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" [(ngModel)]="address.address" name="address_{{address.id}}" placeholder="St. Thomas Apartment"/>
                </div>
          </div>
          <div class="col-6">
              <div class="form-group">
                  <label>Street</label>
                  <input type="text" class="form-control" [(ngModel)]="address.street" name="street_{{address.id}}" 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" [(ngModel)]="address.city" name="city_{{address.id}}" placeholder="Mumbai"/>
                </div>
          </div>
          <div class="col-6">
              <div class="form-group">
                  <label>Country</label>
                  <select class="form-control" [(ngModel)]="address.country" name="country_{{address.id}}" placeholder="India">
                    <option value="india">India</option>
                    <option value="usa">USA</option>
                    <option value="england">England</option>
                  </select>
                </div>
          </div>
        </div>
      </section>

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

</form>


// 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.component.tsimport { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  public addresses: any[] = [{
    id: 1,
    address: '',
    street: '',
    city: '',
    country: ''
  }];
  constructor() {

  }

  ngOnInit() {

  }

  addAddress() {
    this.addresses.push({
      id: this.addresses.length + 1,
      address: '',
      street: '',
      city: '',
      country: ''
    });
  }

  removeAddress(i: number) {
    this.addresses.splice(i, 1);
  }

  logValue() {
    console.log(this.addresses);
  }
}


Conclusion

I hope, this angular template driven forms tutorial helps you to solve how to create multiple inputs in angular. In simple, you should use *ngFor to create multiple inputs.

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...