无法在FormGroup

时间:2018-11-30 18:43:22

标签: 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")
     }
    }

表中未显示经理姓名,并且我不断出现以下错误:-

  

错误错误:找不到路径为'manager_formArray->的控件   setUpControl的_throwError(forms.js:1731)的“ MgrName”   (forms.js:1639)在   FormGroupDirective.push ../ node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl   (forms.js:4456)在   FormControlName.push ../ node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl   (forms.js:4961)在   FormControlName.push ../ node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges   (forms.js:4911)位于checkAndUpdateDirectiveInline(core.js:9031)             在checkAndUpdateNodeInline(core.js:10299)在   在debugCheckAndUpdateNode上检查checkAndUpdateNode(core.js:10261)   (core.js:10894)位于debugCheckDirectivesFn(core.js:10854)   addPM manager-create-modal.component.ts:50之后的列表   另外:[对象对象],[对象对象]         manager-create-modal.component.ts:53 {MgrName:“”}         manager-create-modal.component.ts:53 {MgrName:“”}

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

1 个答案:

答案 0 :(得分:3)

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

当您按下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);
}

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

export interface Bar {
    A?: string;
    B: number; // int32
    C: string; // date-time
    Baz?: Baz;
}
export interface Baz {
    D: number; // decimal
    Color: Color;
}
/**
 * 
 */
export type Color = 0 | 1 | 2;

请检查StackBlitz以获取完整示例