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

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

问题描述

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

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

知道为什么吗?

解决方案

我不知道如何/如果您可以获取动态创建的表单控件的属性名称...但您可以改用您拥有的列表,从中构建表单组.然后你只需要将你得到的列表分配给一个局部变量,这样你就可以在模板中使用它.

首先,如果你想使用运动的name,你需要改变你的创建表单组并使用name代替id:

我会稍微重构一下,为 formarray 使用一个 getter 并执行:

//选择更好的名字 ;)获取 formArr() {将 this.accountForm.get("sports") 作为 FormArray 返回;}

在这种情况下,

fb 指的是 FormBuilder:

this.accountForm = this.fb.group({体育:this.fb.array([])});//…………//不要使用任何,输入你的数据!this.list.forEach((item: any, i) => {this.formArr.push(这个.fb.group({[this.list[i].name]: 假}));});

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

 <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(仅)有角度

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

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

Based on this, I implemented the following

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

Controller

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

  }

But I get the following error:

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

Here is the content of accountForm

Any idea why ?

解决方案

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.

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:

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

Here's a STACKBLITZ with (only) angular

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

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