使用* ngFor遍历包含FormGroups的FormArray

Man*_*UEZ 4 ionic2 angular angular-reactive-forms

在Ionic 2中,我试图创建一个动态表单,该表单应显示一个切换按钮列表。

为此,我尝试使用FormArray并依赖于Angular文档,主要是在这篇文章上

基于此,我实现了以下

<form *ngIf="accountForm" [formGroup]="accountForm">

    <ion-list>

      <!-- Personal info -->
      <ion-list-header padding-top>
        Informations personnelles
      </ion-list-header>
      <ion-item>
        <ion-label stacked>Prénom</ion-label>
        <ion-input formControlName="firstname" [value]="(user | async)?.info.firstname" type="text"></ion-input>
      </ion-item>

      <!-- Sport info -->
      <ion-list-header padding-top>
        Mes préférences sportives
      </ion-list-header>
      <ion-list formArrayName="sports">

        <ion-item *ngFor="let sport of accountForm.controls.sports.controls; let i = index" [formGroupName]="i">
          <ion-label>{{sport.name | hashtag}}</ion-label>
          <ion-toggle formControlName="{{sport.name}}"></ion-toggle>
        </ion-item>

      </ion-list>

    </ion-list>


  </form>
Run Code Online (Sandbox Code Playgroud)

控制者

ionViewDidLoad() {
    console.log('MyAccountPage#ionViewDidLoad');

    // Retrieve the whole sport list
    this.sportList$ = this.dbService.getSportList();
    this.sportList$.subscribe(list => {

      // Build form
      let sportFormArr: FormArray = new FormArray([]);

      for (let i=0; i < list.length; i++) {
        let fg = new FormGroup({});
        fg.addControl(list[i].id, new FormControl(false));
        sportFormArr.push(fg);
      }

      this.accountForm = this.formBuilder.group({
        firstname: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])],
        lastname: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])],
        company: [''],
        sports: sportFormArr
      });

      console.log('form ', this.accountForm);
    })

  }
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

ERROR Error: Cannot find control with path: 'sports -> 0 -> '
Run Code Online (Sandbox Code Playgroud)

这是accountForm的内容在此处输入图片说明

知道为什么吗?

AJT*_*T82 5

我不知道如何/是否可以获取动态创建的表单控件的属性名称...,但是可以利用已有的列表来构建表单组。然后,您只需将要获取的列表分配给局部变量,以便可以在模板中使用它。

首先,如果您想使用name这项运动,则需要更改表单组的创建并使用它name代替id:

fg.addControl(this.list[i].name, new FormControl(false));
Run Code Online (Sandbox Code Playgroud)

然后,如前所述,您可以利用模板中的列表和索引,因此:

 <ion-item *ngFor="let sport of accountForm.controls.sports.controls; let i = index" [formGroupName]="i">
    <ion-label>{{list[i].name}}</ion-label>
    <ion-toggle formControlName="{{list[i].name}}"></ion-toggle>
 </ion-item>
Run Code Online (Sandbox Code Playgroud)

这是一个PLUNKER