Tharindu Sandaruwan
Tharindu Sandaruwan

Reputation: 585

How to add input field dynamically in angular?

**Problem:**

I have an array of the input field properties like this.

    data = [
       {
         name:"FirstName"
       }
       {
         name: "MobileNo",
         min: 10,
         max:14 
       }
    ]

This is my HTML form code.

    <button (click)="addFormFeild()">Add form feilds</button>

    <form
      [formGroup]="distributionAddForm"
      (ngSubmit)="onSubmit(distributionAddForm.value)"
    >
      <div class="form-group">
        <label>Status :</label>
        <div class="input-group input-group-alternative mb-3">
          <input
            class="form-control"
            id="address"
            type="address"
            formControlName="address"
            required
          />
        </div>
      </div>
    </form>

This is my component.ts file code.

    import { Component } from "@angular/core";
    import {
      Validators,
      FormGroup,
      FormArray,
      FormBuilder,
      FormControl
    } from "@angular/forms";

    const data = [{ name: "First Name" }, { name: "MobileNo", min: 10, max: 14 }];

    @Component({
      selector: "app-root",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      public distributionAddForm: any;
      constructor(private formBuilder: FormBuilder) {
        this.distributionAddForm = this.formBuilder.group({
          address: new FormControl("", Validators.required)
        });
      }

       addFormFeild() {
    data.map((item, index) => {

    });
  }

      onSubmit(data) {
        console.log(data);
      }
    }

what I want to do is when clicking on add Form field button it should loop through data array and it should add a form field to distributionAddForm and it should render a form field in the form. I tried a lot of ways to figure out how to do it correctly but I was unable to find out a way to do it. If someone can help me to find out a solution to this problem it would be grateful to me. Here I am providing a sandbox link if needed sandbox. Thank you very much.

Upvotes: 0

Views: 1978

Answers (2)

G&#233;r&#244;me Grignon
G&#233;r&#244;me Grignon

Reputation: 4228

You can use addControl() on your reactive form :

addFormFields(): void {
 data.forEach(item => {
  this.distributionAddForm.addControl(item.name, this.fb.control(''));
 })
}

Loop over the controls inside your template (by the way you don't need to add 'required' on a form tag with a control having Validators.required already) :

<form
      [formGroup]="distributionAddForm"
      (ngSubmit)="onSubmit(distributionAddForm.value)"
    >
    <ng-container *ngFor=let control of form.get('dynamicControls').controls | keyvalue">
      <div class="form-group">
        <label [for]="control.key">{{control.key}}</label>
        <div class="input-group input-group-alternative mb-3">
          <input
            class="form-control"
            [id]="control.key"
            [type]="control.key"
            [formControlName]="control.key"
          />
        </div>
      </div>
    </form>

Upvotes: 1

b1617
b1617

Reputation: 172

You can add to your controls

addFormFeild() {
   data.map((item, index) => {
       this.distributionAddForm.controls[item.name] = new FormControl("",Validators.required);
   });
}

Then just iterate your controls

<div class="form-group">
    <label>Status :</label>
    <div class="input-group input-group-alternative mb-3">
      <input
        class="form-control"
        *ngFor="let control of distributionAddForm.controls | keyvalue"
        formControlName="{{control.key}}"
        placeholder="{{control.key}}"
      />
    </div>
</div>

Upvotes: 1

Related Questions