Add item in dynamic reactive form in Angular

╄→гoц情女王★ 提交于 2019-11-29 11:51:02

So first let start with understanding what you do.

You make a formarray in formarray. So this mean it have two loops. So you have to *ngFor the first and *ngFor the second. In the end this means you have an index i for your items and and j for your subItems. Then you can add addSubItems(i) for pushing your subItems.

Your html should look something like this:

<form [formGroup]="orderForm">
  <div formArrayName="items">
     <div *ngFor="let arrays of orderForm.controls.items.controls; let i = index;">
        <div formGroupName="{{i}}">
          <input formControlName="name" placeholder="Item name">
          <input formControlName="description" placeholder="Item description">
          <input formControlName="price" placeholder="Item price">
          <input type="button" value="subAdd" (click)="addSubItems(i)"> <-- here your button -->
          <div formArrayName="subItems">
             <div *ngFor="let item of arrays.controls.subItems.controls; let j = index;">
                <div formGroupName="{{j}}">
                   <input formControlName="subname" placeholder="Item subname">

Your addSubItems should look something like:

 addSubItems(_index: any): void {
    this.item = this.orderForm['controls']['items']['controls'][_index] as FormGroup;
    this.subItems = this.item.get('subItems') as FormArray;
    this.subItems.push(this.createSubItem());

To reduce amount of code, these can little refactored addSubItems(index) to addSubItems(item):

<form [formGroup]="orderForm">
  ...
  <div formArrayName="items" *ngFor="let item of orderForm.controls.items.controls; let i = index;">
      ...
      <input type="button" value="subAdd" (click)="addSubItems(item)">
  </div>
  ...
</form>

addSubItems(item: FormGroup): void {    
    this.subItems = item.get('subItems') as FormArray;
    var newSubItem = {
      'subname': 'value6'
    }
    this.subItems.push(this.createSubItem(newSubItem));
  }

So, no need to find item by index: var a = this.orderForm['controls']['items']['controls'][_index] as FormGroup;, because you are already can pass item: FormGroup

StackBlitz Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!