Open to work
Published on

Dynamic forms in Angular with examples

Authors

image

Angular provides two ways to create dynamic forms:

  • Template-driven forms: These forms are defined in the HTML template using directives such as ngModel and ngForm. To create a dynamic template-driven form, you can use the *ngFor directive to loop over an array of form controls and create a new input field for each control.
  • Reactive forms: These forms are defined in code using the Angular Forms API. To create a dynamic reactive form, you can use the FormBuilder service to create a FormGroup object. You can then add or remove form controls from the FormGroup at runtime.

We will only discuss about Reactive Forms

Creating a Dynamic Reactive Form

To create a dynamic reactive form in Angular, follow these steps:

  1. Import the necessary modules:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
  1. Define the form controls and form group in your component:
@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
})
export class DynamicFormComponent {
form!: FormGroup;

  medicineOptions = [
    { id: 1, name: 'Medicine 1' },
    { id: 2, name: 'Medicine 2' },
    { id: 3, name: 'Medicine 3' }
  ];

  formGroupArray!: FormArray;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.fb.group({
      medicineArr: this.fb.array([this.createForm()])
    });

    this.formGroupArray = this.form.get('medicineArr') as FormArray;
  }

  get medicineFormGroup() {
    return this.form.get('medicineArr') as FormArray;
  }

  createForm(){
    return this.fb.group({
      medicine: [null],
      amount: [''],
      dosage: [null],
      duration: [null]
    });
  }

  1. Create methods to add and remove dynamic form controls:

  addFormGroup() {
    const formGroup = this.fb.group({
      medicine: [''],
      amount: [''],
      dosage: [''],
      duration: ['']
    });

    this.formGroupArray.push(formGroup as never);
    this.form.addControl('medicineArr', formGroup);
  }
  1. Bind the form controls to the template:
<form [formGroup]="form" (submit)="onSubmit()">
            <h2>Add Medicine</h2>
            <div formArrayName="medicineArr">
              <div *ngFor="let contact of medicineFormGroup.controls; let i = index;">
                <div [formGroupName]="i" class="mt-4">
                  <div class="form-group">
                    <ng-select [items]="medicineOptions" bindLabel="name" bindValue="id" formControlName="medicine"
                      placeholder="Select medicine">
                    </ng-select>
                  </div>

                  <div class="form-group mt-2">
                    <input type="number" formControlName="amount" class="form-control">
                  </div>

                  <div class="form-group mt-2">
                    <ng-select [items]="medicineOptions" bindLabel="name" bindValue="id" formControlName="medicine"
                    placeholder="Select medicine">
                  </ng-select>
                  </div>

                  <div class="form-group mt-2">
                    <ng-select [items]="medicineOptions" bindLabel="name" bindValue="id" formControlName="medicine"
                    placeholder="Select medicine">
                  </ng-select>
                  </div>

                </div>
              </div>
            </div>
            <div class="mt-2">
            <button type="button" class="btn btn-primary mx-1" (click)="addFormGroup()">Add More</button>
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
          </form>
  1. See result on console on submit
  onSubmit() {
    console.log(this.form.value);
  }

Now, you have a dynamic reactive form that allows users to add and remove form controls dynamically.

Checkout this git repo for working example https://github.com/rabbyalone/dynamic-forms