Dynamically add a set of fields to a reactive form

Anna Olshevskaia picture Anna Olshevskaia · Jul 20, 2018 · Viewed 13.5k times · Source

I have 2 input fields: name and last name. I have 2 buttons: submit and 'add a person'. Clicking on 'add a person' should add a new set of fields (name and last name). How to achieve that? I found solutions how to add single input fields dynamically, but here I need to add a set

My code now without 'add a person' functionality:

import { FormControl, FormGroup, Validators } from '@angular/forms';
export class AppComponent implements OnInit {
   form: FormGroup;
   constructor(){}
   ngOnInit(){
     this.form = new FormGroup({
       name: new FormControl('', [Validators.required, Validators.minLength(2)]),
       lname: new FormControl('', [Validators.required, Validators.minLength(2)])
     });
   }
 ....
 }

template:

<form [formGroup]="form" (ngSubmit)="submit()">
    Name: <input type="text" formControlName="name">
    Last Name: <input type="text" formControlName="lname">
    <button type="button">Add a Person</button>
    <button type="submit">Submit</button>
</form>

Answer

Marcin Tomczyk picture Marcin Tomczyk · Jul 20, 2018

What you need is FormArray. Given multiple elements with two FormControls name and surname like in your example you could do this: https://stackblitz.com/edit/angular-ztueuu

Here is what's happening:

You define form group as you did but create it with one field of FormArray type

ngOnInit() {
  this.form = this.fb.group({
    items: this.fb.array([this.createItem()])
  })
}

Next you define helper method we use above createItem() to make us group with set of controls you want to multiply

createItem() {
  return this.fb.group({
    name: ['Jon'],
    surname: ['Doe']
  })
}

And lastly the method you wanted to multiply items in this set:

addNext() {
  (this.form.controls['items'] as FormArray).push(this.createItem())
}

Combine this with html below. We are iterating over array items and displaying fields from group. Form group name here is index of array.

<form [formGroup]="form" (ngSubmit)="submit()">
  <div formArrayName="items"
    *ngFor="let item of form.controls['items'].controls; let i = index">
    <div [formGroupName]="i">
      <input formControlName='name'>
      <input formControlName='surname'>
    </div>
  </div>
  <button type="button" (click)="addNext()">Add Next</button>
  <button type="submit">Submit</button>
</form>

And you can create form with expanding set of items.