使用* ngFor遍历包含FormGroups的FormArray [英] Iterating through a FormArray containing FormGroups with *ngFor

查看:387
本文介绍了使用* ngFor遍历包含FormGroups的FormArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Ionic 2 I am trying to create a dynamic form which shall display a list of toggle buttons.

为此,我尝试使用FormArray并依赖于Angular文档,主要依靠发布

To do so I am trying to use a FormArray and relied on the Angular doc and mainly on this post

基于此,我实现了以下

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

控制器

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);
    })

  }

但是出现以下错误:

ERROR Error: Cannot find control with path: 'sports -> 0 -> '

这是accountForm

Here is the content of accountForm

知道为什么吗?

推荐答案

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

I don't how/if you can tap into getting the property name of of a dynamically created formcontrol... but you can utilize the list you have instead, from which you are building the formgroups. Then you just have to assign the list you are getting to a local variable, so that you can use it in template.

首先,如果要使用运动的name,则需要更改表单组的创建并使用name而不是id:

First off, if you want to use the name of the sport, you need to change your creation the formgroup and use name instead of id:

然后我将对其进行一些重组,将吸气剂用于formarray并执行以下操作:

And I would restructure this a bit, use a getter for the formarray and do:

// choose better name ;)
get formArr() {
  return this.accountForm.get("sports") as FormArray;
}

在这种情况下,

fb指的是FormBuilder:

fb refers to FormBuilder in this case:

this.accountForm = this.fb.group({
  sports: this.fb.array([])
});

// ...........

// don't use any, type your data!
this.list.forEach((item: any, i) => {
  this.formArr.push(
    this.fb.group({
      [this.list[i].name]: false
    })
  );
});

然后,您可以在模板中使用列表和索引,因此:

Then as said, you can utilize the list and the index in template, so:

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

这是 STACKBLITZ (仅)成角形

Here's a STACKBLITZ with (only) angular

这篇关于使用* ngFor遍历包含FormGroups的FormArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆