Add item in dynamic reactive form in Angular

后端 未结 2 419
鱼传尺愫
鱼传尺愫 2020-12-19 22:04

I am trying to build a nested reactive form in Angular 5. I am able to push items at one level, but unable to push item at second level.

ngOnInit() {
 this.         


        
相关标签:
2条回答
  • 2020-12-19 22:44

    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());
    
    0 讨论(0)
  • 2020-12-19 22:47

    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

    0 讨论(0)
提交回复
热议问题