All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Adding Form Fields Dynamically In Angular 6

Last Updated : Mar 11, 2024

Adding Form Fields Dynamically In Angular 6

In this tutorial we will show you the solution of adding form fields dynamically in angular 6, in our application we created form with collecting product details like product name, price and quantity by dynamically.

Dynamically means it will change according to user input not a standard layout.

When user gives input it will add to table and displayed as an array then we can remove those added row also from the table.

Step By Step Guide On Adding Form Fields Dynamically In Angular 6 :-

Here user can do either add input fields or remove those by importing FormGroup, FormArray and FormBuilder from angular library.

FormGroup is used with FormControl to track the value and validate the state of form control.

The FormBuilder is the helper API to build forms in angular. It provides shortcuts to create the instance of the FormControl, FormGroup or FormArray.

It reduces the code required to write the complex forms. The FormArray is a way to manage collection of from controls in angular.

Using FormGroup library we grouped input fields of ‘quantity and price’ and the final result of ‘product name, quantity and price’ as a group.

Src/app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule, ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Src/app/app.component.ts

import { FormGroup, FormControl, FormArray, FormBuilder } from '@angular/forms'
export class AppComponent {
  title = 'NewProgram';
  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);
}
}

Src/app/app.component.html

<div class="container">
<h1>Adding form fields dynamically</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 formArrayName="quantities">
  <tr>
  <th colspan="2">Add Multiple Quantity:</th>
  <th width="150px"><button type="button" (click)="addQuantity()">Add More</button></th>
  </tr>
  <tr *ngFor="let quantity of quantities().controls; let i=index" [formGroupName]="i">
  <td>
              Quantity :
  <input type="text" formControlName="qty">
  </td>
  <td>
              Price:
  <input type="text" formControlName="price">
  </td>
  <td>
  <button (click)="removeQuantity(i)">Remove</button>
  </td>
</tr></table>
    <button type="submit">Submit</button>
    </form>
    <br/>
    {{this.productForm.value | json}}
</div>
  1. In app.module.ts file we need to import ‘FormsModule, ReactiveFormsModule’ libraries at header then need to write same on the imports array because as we know for getting supports when we write related code on component file.
  2. In app.component.html file within container we defined our form with table and submit button. In table we defined two more input fields and remove button.
  3. In form ‘[formGroup]’ used to grouped our form elements and our form group name is ‘productForm’. Using ‘ngSubmit’ when user submit form it loads ‘onSubmit()’ function.
  4. When group some html elements we need to specify ‘formControlName’ attribute at each elements so now we can group any html elements in form.
  5. In our we created label for each <input> tag for user clarification and its labeled by attribute ‘for’ with <input> tag id attribute.
  6. Our table we make it as array using FormArray so we defined ‘formArrayName’ attribute in table and table header merged first two columns by ‘colspan=2’ and in next column we created ‘Add More’ button.
  7. The ‘Add More’ button used for create three dynamic ‘input field’ in table after header row with information of product quantity, price and remove option. When user clicks on ‘Add More’ button it loads ‘addQuantity()’ function.
  8. In table row ‘*ngFor’ creates index for each dynamic row when users clicks on ‘Add More’ and those each two columns grouped by index ‘i’. Using index ‘i’ we can remove that particular row from the table. When user clicks on ‘Remove’ button it loads ‘removeQuantity()’ function.
  9. Finally we displayed our array values in json format. In ‘app.component.ts’ file we defined each function we called at ‘app.component.html’ file.
  10. Here we defined constructor as we seen FormBuilder used to create shortcuts for instance so here we used form builder as ‘fb’ used that we all user values and stored to ‘productForm’.
  11. In ‘addQuantity()’ function we called quantity() function with newQuantity() function values. So in newQuantity() function we are grouping ‘qty,price’ values and returns to ‘fb’ as a group. Then with that user values in quantity() function we make it as array and returned to ‘productForm’.
  12. In ‘removeQuantity()’ function removing that index values from array and in ‘onSubmit()’ function we printed ‘productForm’ array values on console.

Conclusion :-

In conclusion now we are able to know how to add or remove form fields dynamically using angular.

For seeing result on webpage we need to support of server and internet connection.

As we know commend ‘ng serve’ will execute our code on server port ‘localhost:4200’.

Initially our result is empty so we need to give input of product name then clicks on add more will ask two more inputs ‘quantity and price’.

After filled user input when user clicks on submit it displays result at last line and also on console we can see the array of result.

I hope this tutorial on adding form fields dynamically in angular 6 helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Ashish

Ashish is a dynamic and motivated individual with a passion of programming and an experienced programmer having 3+ years of experience in various languages like Java, Python, HTML, CSS, JavaScript, jQuery and various frameworks like Bootstrap

Follow Ashish On Linkedin 🡪