使用Angular formArray动态添加表单字段

时间:2018-06-27 04:40:01

标签: angular

我有几个表单字段,并且想动态添加来自另一个视图的更多字段(用户可以在其中输入表单字段的类型,长度和名称),我需要使用这些值来构造表单字段。

有些方法我设法构造了一个字段(textbox name is 'one'),但是如果我尝试添加另一个字段(textbox name is 'two'),则会收到以下错误消息,

ERROR Error: Cannot find control with path: 'newfields -> 0 -> two' 

issuecomponent.html

  <form [formGroup]="issuerTestCaseFrm">
                <div>
                    <label for="inputName3">Issuer Reference Number: </label>
                    <input name="lcid" formControlName="IssuerReferenceNumber" required type="tel" class="form-control">
                </div>
                    <div formArrayName="newfields">
                    <div [formGroupName]="i" *ngFor="let tech of issuerTestCaseFrm.controls.newfields.controls; let i = index">
                    <div *ngFor="let prop of fieldProps">
                                <label class="col-sm-2 control-label">{{fields[prop].label}}</label>
                                <div [ngSwitch]="fields[prop].type">
                                    <input *ngSwitchCase="'text'" [formControlName]="prop"> 
                                </div>
                        </div>
                    </div>
                </div>  
    </form>
<button type="submit" (click)="addNewInputField()"> &nbsp;Add New Column &nbsp; </button>

issuecomponent.ts

import { Component, ViewEncapsulation, Pipe, PipeTransform, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl, FormArray } from '@angular/forms';
import { ModalComponent } from '../../modal/modal.component';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
  selector: 'viewhistory',
  templateUrl: './issuecomponent.html',
})


export class IssuerTestcaseExecution implements OnInit {
  issuerTestCaseFrm: FormGroup;
  fields: any;
  fieldProps: any;
  formControls = {};
  constructor( 
    private fb: FormBuilder,  
    public modalService: NgbModal,
    ) {
    this.issuerTestCaseFrm = fb.group({
      'IssuerReferenceNumber': ['', Validators.required],
      'newfields': fb.array([]),
    });
  }

  initNewFields(): FormGroup {
    this.fieldProps.forEach(prop => {
      this.formControls[prop] = [this.fields[prop].value, Validators.required];
    });
    return this.fb.group(this.formControls);
  }

 //Assuming these results coming from modal view after add button click
  addNewInputField(): void {
      const modalRef = this.modalService.open(ModalComponent);
      modalRef.result.then((result) => {
         this.fields = {
          [result.fieldname]: {
            type: result.fieldtype,
            value: result.fieldvalue,
            label: result.fieldname,
          },
        };
        this.fieldProps = Object.keys(this.fields);
         const control = <FormArray>this.issuerTestCaseFrm.controls.newfields;
         control.push(this.initNewFields());
      }, (reason) => {

      });
  }
}

我在stackblitz.com中添加了示例代码。任何机构都可以在此问题上提供帮助: https://stackblitz.com/edit/angular-871vxk?file=src/app/app.component.ts

1 个答案:

答案 0 :(得分:0)

尽管这不能完全为您提供帮助,但是需要对表单和组件进行一些更改以消除此错误

  1. 将表单字段更改为新的FormArray()

     this.issuerTestCaseFrm = fb.group({
       'IssuerReferenceNumber': ['', Validators.required],
       'technologies': new FormArray([]),
    });
    
  2. 在组件文件中创建格式为technologies的吸气剂。

    get technologies(): FormArray { return this.issuerTestCaseFrm.get('technologies') as FormArray; }
    
  3. HTML中的
  4. 使用此方法,将formArrayname与*ngFor一起添加,然后在输入字段中添加[formControlName] =“ i”。

    <div [formGroupName]="i" *ngFor="let tech of technologies.controls; let i = index" formArrayName="technologies">
    
    <input class="form-control" *ngSwitchCase="'text'" [formControlName]="i">
    
  5. 当您单击添加按钮时,请使用control.push(new FormControl())

现在您必须在这里工作,如何添加完整的表单域

这是updated demo

Angular FormArray Reference