迭代Angular 2+ FormArray

BBa*_*ger 17 angular angular-reactive-forms

我有一个FormArray,需要遍历每个成员.

我搜索过,发现很多帖子似乎应该有答案,但我仍然没有找到我需要的东西.

我看到文档中有一个get方法,但我看不到在哪里获得密钥,甚至长度.

如何迭代FormArray?

Ale*_*esD 24

你有一个属性controlsFormArray其中是一个数组AbstractControl对象.检查FormArray的特定文档,您将看到它们也AbstractControlFormControl您发布的那样继承.

请注意,在控件数组中,您可以再次在对象内部FormArrayFormGroup对象之外的FormControl对象,因为可以有嵌套组或数组.

这是一个简单的例子:

for (let control of formArray.controls) {
   if (control instanceof FormControl) {
      // is a FormControl
   }
   if (control instanceof FormGroup) {
      // is a FormGroup  
   }
   if (control instanceof FormArray) {
      // is a FormArray
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 不知道为什么没有记录在案。 (2认同)
  • [这个答案](/sf/answers/2956465431/)帮助了我:`this.form = this.fb.group({ userIds: this.fb.array([]) }); const userIds = this.form.controls.userIds as FormArray; userIds.value.forEach(key => { this.clinet.updateContactGroup(key, this.groupId).subscribe();} );` (2认同)

Ous*_*ama 7

我通过循环解决了这个问题formArray.controls

  formArray.controls.forEach((element, index) => {
    ...
  });
Run Code Online (Sandbox Code Playgroud)


O95*_*O95 5

如果有人需要帮助在模板中迭代它们(就像我一样),你可以这样做。

在本例中,我们有 FormArray,其中每个子项都是 FormControl

get myRows(): FormControl[] {
    return (this.<your form group>.get('<field name>') as FormArray).controls as FormControl[];
  }
Run Code Online (Sandbox Code Playgroud)

并在模板中

*ngFor="let row of myRows"
Run Code Online (Sandbox Code Playgroud)