当FormArray嵌套在另一个FormArray中时如何获取FormArrayName?

时间:2017-06-08 06:52:58

标签: arrays forms angular nested getter

参考:https://angular.io/docs/ts/latest/api/forms/index/FormArrayName-directive.html,很容易获得FormArrayName:

HTML:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div formArrayName="cities">
    <div *ngFor="let city of cities.controls; index as i">
       <input [formControlName]="i" placeholder="City">
    </div>
  </div>
  <button>Submit</button>
</form>

TS:

form = new FormGroup({
  cities: new FormArray([
    new FormControl('SF'),
    new FormControl('NY'),
  ]),
});

get cities(): FormArray { return this.form.get('cities') as FormArray; } 
// This does the magic!

DOM <div formArrayName="cities"> 使用吸气剂 get cities(): FormArray { return this.form.get('cities') as FormArray; } 一切都像魅力一样

BUT

当FormArray嵌套在另一个FormArray中时如何制作getter?

让我们说这个例子:

TS:

form = new FormGroup({
  cities: new FormArray([
    new FormGroup({ 
      name: new FormControl('SF'),
      sisterCities: new FormArray(['Shanghai','Zurich',...])
    }),
    new FormGroup({
      name: new FormControl('NY'),
      sisterCities: new FormArray(['London','Oslo',...])
    }),
  ]),
});

get cities(): FormArray { return this.form.get('cities') as FormArray; } 
// still get the main cities FormArray

// but 
// get sisterCities() won't work because I need to target a city FormGroup (NY or SF) before accessing its sisterCities FormArray.
// and AFAIK, it is not possible to pass parameters to a getter.

HTML:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div formArrayName="cities">
    <div *ngFor="let city of cities.controls; index as i" [formGroupName]="i">
       <input [formControlName]="name" placeholder="City">
       <div formArrayName="sisterCities"> <!-- this will never work -->
         <div *ngFor="let sisterCity of sisteCities.controls; index as j">
           ...
         </div>
       </div>
    </div>
  </div>
  <button>Submit</button>
</form>

请帮助我实现这一目标。 提前谢谢。

2 个答案:

答案 0 :(得分:4)

我在努力解决同样的问题。并最终解决了它。 首先,我们寻找主要形式阵列'城市'结构。

Nested FormArray structure

图像中的黄色高位控件是第一个数组控制路径。 =&GT; cities 绿色高位控制是第二个阵列控制。 =&GT; sisterCities

    <form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div formArrayName="cities">
    <div *ngFor="let city of cities.controls; index as i" [formGroupName]="i">
       <input [formControlName]="name" placeholder="City">
       <div formArrayName="sisterCities"> <!-- this will never work -->
         <div *ngFor="let sisterCity of cities.controls[i]sisterCities.controls; index as j">
           ...
         </div>
       </div>
    </div>
  </div>
  <button>Submit</button>
</form>

访问第二个嵌套的FormArray的正确方法是在插入当前城市索引后访问第一个控件数组。分别为sisterCitiescontrol

let sisterCity of cities.controls[i].sisterCities.controls

答案 1 :(得分:0)

与嵌套表单组一样,它对我来说就像是一种魅力..您需要:

  1. 使用[formGroupName] =“ i”
  2. formControlName不能是动态的。相反,它应该具有在初始化from组时使用的名称,并且有无数示例。
  3. 您需要在与使用formArrayName属性相同的div中迭代表单数组控件。