Dynamically creating input forms in Angular2

前端 未结 1 562
被撕碎了的回忆
被撕碎了的回忆 2021-01-16 02:05

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 p

相关标签:
1条回答
  • 2021-01-16 02:26

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

    0 讨论(0)
提交回复
热议问题