首页 文章

无法在FormGroup中存储动态FormArray

提问于
浏览
2

我有一个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")
     }
    }

经理名称未显示在表格中,我继续收到以下错误: -

错误错误:无法在FormGroupDirective.push ../ node_modules / @ angular / forms / fesm5 /的setUpControl(forms.js:1639)的_throwError(forms.js:1731)找到路径:'manager_formArray - > MgrName'的控件FormControlName.push上的FormControlName.push ../ node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl(forms.js:4961)中的forms.js.FormGroupDirective.addControl(forms.js:4456)..在checkAndUpdateNodeInline(core.js:10299)的checkAndUpdateNireInline(core.js:10299)的checkAndUpdateNode(core.js:10261)处的/node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges(forms.js:4911) )在debugCheckAndUpdateNode(core.js:10894)的debugCheckDirectivesFn(core.js:10854)中,addPM manager-create-modal.component.ts:添加后的50个列表:[object Object],[object Object] manager-create-modal .component.ts:53 {MgrName:“”} manager-create-modal.component.ts:53 {MgrName:“”}

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

1 回答

  • 3

    你有一些问题 . 首先,最好移动输入,在 <div formArrayName="manager_formArray"> 元素之外的 FormArray 中添加更多 FormGroup . 我出于这个原因创建了一个新的FormControl this.mgrNameInput = new FormControl(''); (有关详细信息,请参阅StackBlitz) .

    当您按 Add 按钮,调用 addPM() -method时,还需要将消息添加到新条目:

    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.
    }
    

    我还在删除条目时添加了remove-method .

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

    请查看StackBlitz以获取完整示例

相关问题