Search code examples
javascriptangulartypescriptangular-reactive-formsangular-forms

Angular : set reactive form with dynamic looping inputs


I've to set reactive form validation for a form where the inputs are made with data looping :

my form builder would look like this :

constructor(private formBuilder: FormBuilder) { 
    this.userForm = this.formBuilder.group({
      'inputOne': ['', [Validators.required]],
      'inputOne': ['', [Validators.required]],
       ...
      'inputN': ['', [Validators.required]]
    });
  }

and my template would look like this :

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="item.name">
      </div>
</form>

where items are loaded dynamically from my my backend

How to populate controls dynamically in Angular reactive forms?


Solution

  • sounds like you want a form array here, not a group...

      constructor(private formBuilder: FormBuilder) { 
        // build an empty form array
        this.userForm = this.formBuilder.array([]); 
      }
    
      // call this whenever you need to add an item to your array
      private addItem(item) {
        // build your control with whatever validators / value
        const fc = this.formBuilder.control(i.lastName, [Validators.required]);
        this.userForm.push(fc); // push the control to the form
      }
    
      // call this function whenever you need to reset your array
      private resetFormArray(items) {
        this.userForm.clear(); // clear the array
        items.forEach(i => this.addItem(i)); // add the items
      }
    
    <form [formGroup]="userForm">
      <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="i">
      </div>
    </form>
    

    notice you're using the index for the form control name here