1

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 want to display that many forms to the user.

Like this:

<ion-list *ngFor="let item of numberOfGuests">
    <ion-item>
      <ion-label>Full name</ion-label>
      <ion-input type="text"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Age</ion-label>
      <ion-input type="number"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Grade</ion-label>
      <ion-input type="number"></ion-input>
    </ion-item>
  </ion-list>

The above obviously does not work. I am just using that as an example. I want each list or form of inputs to be created based on how many guests the user wants to bring.

Is this even possible within Angular 2? Is it possible to dynamically create a form in html based on a numeral?

0

1 Answer 1

2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.