How to get FormArrayName when the FormArray is nested in another FormArray?

一曲冷凌霜 提交于 2019-12-03 08:47:31

I struggling same problem. And finaly solved it. Firstly we looking to main form array 'cities' structure.

Which is the yellow highlited controls at image is first array control path. => cities And green highlited control is second array control. => 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>

Proper way to access this second nested FormArray is accessing first control array after insert current cities index. And respectively sisterCities,control.

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

it worked like a charm for me same as nested form groups .. you need to:

  1. use [formGroupName]="i"
  2. formControlName cannot be dynamic .. instead it should have the name that you when you initialized the from group and there are countless example for that.
  3. you need to iterate over the form array controls in the same div that you used formArrayName attribute in.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!