无法在 FormGroup 中存储动态 FormArray

Not able to store dynamic FormArray in FormGroup

我有一个 FormGroup,它有三个 FormControl 字段和一个 FormArray 字段,如下图所示。要求是从用户那里获取经理姓名,按下添加按钮后,经理详细信息应显示在 table 中。在 table 中提供了一个删除按钮,当按下删除按钮时,管理器应该从 table 和列表中删除。提交表单时,应保存经理列表。除 formArray 逻辑外,一切正常。

我试图在网上找到这个问题的解决方案(点击各种链接:- https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/),但没有多大帮助。关于如何将formArray 存储在formGroup 中的内容不多material。请推荐。

下面是我的代码,请看一下:-

1. manager-create-modal.component.html

<div>
    <form [formGroup]="createForm" (ngSubmit)="onFormCreation()">
        <div class="row">
             <div class="column">
               <div class="form-inline">
                 <div class="form-group">
                    <label for="remote_access_method">Remote Access Method: <font color="orange"> *</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                      <input type="text" size='38' class="form-control" formControlName="remote_access_method" >
                 </div>
                </div>
               <br>
               <div class="form-inline">
                 <div class="form-group">
                    <label for="status">Current Status: <font color="orange"> *</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                    <input type="text" size='38' class="form-control" formControlName="status">
                 </div>
               </div>
               <br>
               <div class="form-inline">
                 <div class="form-group">
                   <label for="secregid">Registration ID:<font color="orange"> *</font> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                   <input type="text" size='38' class="form-control" formControlName="secregid">
                 </div>
               </div>
               <br><br>
               <div class="form-inline">
                 <div class="form-group">
                    <br><br>
                    <div formArrayName="manager_formArray">
                      Enter name: <input type="text" class="form-control" formControlName="MgrName" size='50' >&nbsp;&nbsp;
                      <button type="button" class="btn btn-primary btn-sm" (click)="addPM()">Add</button>
                        <br><br>
                        <table class="table table-hover">
                          <tr><th>#</th><th>Manager Name</th><th>Remove</th></tr>
                          <tr *ngFor="let pm of createForm.get('manager_formArray').value; let id = index">
                              <td>{{id+1}}</td>
                              <td>{{pm.MgrName}}</td>
                              <td>
                                <span class="table-remove">
                                  <button type="button" class="btn btn-primary btn-sm" (click)="removeMgr(id)">Remove</button>
                                </span>
                              </td>
                          </tr>
                        </table>
                    </div>
                 </div>
               </div>
              </div>
              <br>
            </div>
            <br><br>
            <div class="form-group">
            <button class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>

2。 manager-create-modal.component.ts

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormBuilder, FormArray, FormControl, Validators } from '@angular/forms';


    @Component({
      selector: 'app-manager-create-modal',
      templateUrl: './manager-create-modal.component.html',
      styleUrls: ['./manager-create-modal.component.css']
    })
    export class ManagerCreateModalComponent implements OnInit {

      createForm: FormGroup;
      manager_formArray: FormArray;
      remote_access_method: FormControl;
      status: FormControl;
      secregid: FormControl;

      constructor(private formBuilder: FormBuilder) { }

      createFormControls(){
        this.remote_access_method = new FormControl('');
        this.status = new FormControl('');
        this.secregid  = new FormControl('');
        this.manager_formArray = new FormArray([ this.createItem() ]);
      }

      createItem(): FormGroup {
          return this.formBuilder.group({
            MgrName: ''
          });
      }

      createFormVariables(){
          this.createForm = new FormGroup({
            remote_access_method  : this.remote_access_method,
            status  : this.status,
            secregid   : this.secregid,
            manager_formArray: this.manager_formArray,
          })
      }

      ngOnInit() {
          this.createFormControls();
          this.createFormVariables();
      }

      addPM(mgr: any): void {
          console.log("inside addPM");
          this.manager_formArray.push(this.formBuilder.group({MgrName:''}));
          console.log("list after addition:"+this.manager_formArray.value);

          for(let i = 0; i < this.manager_formArray.length; i++) {
             console.log(this.manager_formArray.at(i).value);
          }
      }

      get managerFormArray() {
       return this.manager_formArray.get('MgrName') as FormArray;
     }

     onFormCreation(){
       console.log("success")
     }
    }

管理员姓名未显示在 table 中,我一直收到以下错误:-

ERROR Error: Cannot find control with path: 'manager_formArray -> MgrName' at _throwError (forms.js:1731) at setUpControl (forms.js:1639) at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:4456) at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:4961) at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:4911) at checkAndUpdateDirectiveInline (core.js:9031) at checkAndUpdateNodeInline (core.js:10299) at checkAndUpdateNode (core.js:10261) at debugCheckAndUpdateNode (core.js:10894) at debugCheckDirectivesFn (core.js:10854) inside addPM manager-create-modal.component.ts:50 list after addition:[object Object],[object Object] manager-create-modal.component.ts:53 {MgrName: ""} manager-create-modal.component.ts:53 {MgrName: ""}

我什至不明白为什么元素没有被添加到 manager_formArray。请帮帮我。

您有一些问题。首先,最好将添加更多 FormGroup 的输入移到 <div formArrayName="manager_formArray">- 元素之外的 FormArray。为此,我创建了一个新的 FormControl this.mgrNameInput = new FormControl('');(有关详细信息,请参阅 StackBlitz)。

您还需要在按下 Add 按钮时将消息添加到新条目,调用 addPM() 方法:

addPM(){ // removed the argument, using the controller inside the method instead.
    this.manager_formArray.push(this.formBuilder.group({MgrName:this.mgrNameInput.value}));
    this.mgrNameInput.reset(); // reset the input field.
}

我在删除条目时还添加了删除方法。

removeMgr(index: number){
    this.manager_formArray.removeAt(index);
}

请检查 StackBlitz 以获得完整示例