html - 无法在 FormGroup 中存储动态 FormArray

标签 html angular typescript angular6 formarray

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

enter image description here

我尝试在网上找到解决方案(遵循各种链接:- https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/Angular 4 Form FormArray Add a Button to add or delete a form input row ),但没有多大帮助。关于如何在formGroup中存储formArray的资料并不多。请提出建议。

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

<强>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")
     }
    }

经理姓名未显示在表格中,我不断收到以下错误:-

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发送至您的FormArray <div formArrayName="manager_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完整示例

关于html - 无法在 FormGroup 中存储动态 FormArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53563159/

相关文章:

Angular 表单模块禁用以前工作的表单

Angular : how to trigger bindings manually?

jquery - 只需要显示 4 个列表 - slideDown jquery

html - 居中固定宽度的元素比流体父更宽?

php - 无需编辑 .js 文件的 Javascript onclick html 字段值

获取未定义值时 Angular "ngif"不起作用

javascript - jquery中的灯箱居中

angular - 升级到 RC 6 和 RxJS Beta 11 后 flatMap 丢失

javascript - 返回接口(interface)或扩展接口(interface)的数组

Angular 10 : Unable to write a reference