Skip to content Skip to sidebar Skip to footer

Dynamically Creating Input Forms In Angular2

I am trying to prompt a user to fill out a form (just name, grade and age) for each number of guest they want. I first ask them how many guests they want. Then on the next page I w

Solution 1:

I would go with a reactive form, just like suggested by Ajmal.

So when you have that value of how many guests should be rendered in template, just push that many formgroups to your form array:

constructor(public navCtrl: NavController, private fb: FormBuilder) {
  // build form
  this.myForm = fb.group({
    // declare empty form array
    guests: fb.array([])
  })
  // here we push form groups to formarray
  this.addGuests();
}

addGuests() {
  let formArr = this.myForm.controls.guests as FormArray;
  // 'amountOfGuests' is the amount of guests you want rendered
  for(let i = 1; i <= this.amountOfGuests; i++) {
    formArr.push(this.fb.group({
      fullName: [''],
      age: [''],
      grade: ['']
    }))
  }
}

Then you just iterate the form array in your template (shortened code):

<form [formGroup]="myForm">
  <ng-container formArrayName="guests">
    <ion-list *ngFor="let guest of myForm.controls.guests.controls; let i = index" [formGroupName]="i">
      <ion-item>
        <ion-label>Full name</ion-label>
        <ion-input formControlName="fullName"></ion-input>
      </ion-item>    
    </ion-list>
  </ng-container>
</form>

Here's a DEMO :)


Post a Comment for "Dynamically Creating Input Forms In Angular2"