使用Angular formArray动态添加表单字段 [英] Dynamically adding form fields using Angular formArray

查看:145
本文介绍了使用Angular formArray动态添加表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a few form fields and want to add more fields dynamically which is coming from another view(where user can enter the form field type, length and name), I Need to construct form fields using these values.

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

Some how i have managed to construct one field(textbox name is 'one') but if i try to add another field(textbox name is 'two') getting the following error saying,

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

I have added sample code in stackblitz.com. can any body help on this issue: https://stackblitz.com/edit/angular-871vxk?file=src/app/app.component.ts

推荐答案

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

although this does not help you completely but there need some changes in form and component to remove this error

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

  1. change form field to new FormArray()

 this.issuerTestCaseFrm = fb.group({
   'IssuerReferenceNumber': ['', Validators.required],
   'technologies': new FormArray([]),
});

  • 在组件文件中创建格式为technologies的吸气剂.

  • create getter of form filed technologies in the component file.

    get technologies(): FormArray { return this.issuerTestCaseFrm.get('technologies') as FormArray; }
    

  • HTML中的
  • 使用这种方式,在*ngFor中添加formArrayname并在输入字段中添加[formControlName] ="i".

  • in HTML use this way, add formArrayname along with *ngFor and add [formControlName]="i" in your input field.

    <div [formGroupName]="i" *ngFor="let tech of technologies.controls; let i = index" formArrayName="technologies">
    
    <input class="form-control" *ngSwitchCase="'text'" [formControlName]="i">
    

  • 当您单击添加按钮时,请使用control.push(new FormControl())

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

    now here you have to work how to add complete formfield

    这是更新的演示

    Angular FormArray参考

    这篇关于使用Angular formArray动态添加表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆