动态地将一组字段添加到反应形式 [英] Dynamically add a set of fields to a reactive form

查看:76
本文介绍了动态地将一组字段添加到反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个输入字段:名称和姓氏. 我有2个按钮:提交"和添加一个人".单击添加一个人"应添加一组新字段(姓名和姓氏). 如何实现呢?我找到了如何动态添加单个输入字段的解决方案,但是在这里我需要添加一个集合

I have 2 input fields: name and last name. I have 2 buttons: submit and 'add a person'. Clicking on 'add a person' should add a new set of fields (name and last name). How to achieve that? I found solutions how to add single input fields dynamically, but here I need to add a set

我的代码现在没有添加人"功能:

My code now without 'add a person' functionality:

import { FormControl, FormGroup, Validators } from '@angular/forms';
export class AppComponent implements OnInit {
   form: FormGroup;
   constructor(){}
   ngOnInit(){
     this.form = new FormGroup({
       name: new FormControl('', [Validators.required, Validators.minLength(2)]),
       lname: new FormControl('', [Validators.required, Validators.minLength(2)])
     });
   }
 ....
 }

模板:

<form [formGroup]="form" (ngSubmit)="submit()">
    Name: <input type="text" formControlName="name">
    Last Name: <input type="text" formControlName="lname">
    <button type="button">Add a Person</button>
    <button type="submit">Submit</button>
</form>

推荐答案

您需要的是FormArray.给定具有两个FormControls名称和姓氏的多个元素,例如在您的示例中,您可以执行以下操作: https://stackblitz.com/edit/angular-ztueuu

What you need is FormArray. Given multiple elements with two FormControls name and surname like in your example you could do this: https://stackblitz.com/edit/angular-ztueuu

这是正在发生的事情:

您可以像定义表格组一样,但是使用一个FormArray类型的字段创建它

You define form group as you did but create it with one field of FormArray type

ngOnInit() {
  this.form = this.fb.group({
    items: this.fb.array([this.createItem()])
  })
}

接下来,您定义我们在createItem()上方使用的帮助程序方法,以使我们与要乘法的控件集组合在一起

Next you define helper method we use above createItem() to make us group with set of controls you want to multiply

createItem() {
  return this.fb.group({
    name: ['Jon'],
    surname: ['Doe']
  })
}

最后,您要对这个集合中的项目进行乘法的方法:

And lastly the method you wanted to multiply items in this set:

addNext() {
  (this.form.controls['items'] as FormArray).push(this.createItem())
}

在下面用html将其合并.我们正在遍历数组项并显示组中的字段.表单组名称是数组的索引.

Combine this with html below. We are iterating over array items and displaying fields from group. Form group name here is index of array.

<form [formGroup]="form" (ngSubmit)="submit()">
  <div formArrayName="items"
    *ngFor="let item of form.controls['items'].controls; let i = index">
    <div [formGroupName]="i">
      <input formControlName='name'>
      <input formControlName='surname'>
    </div>
  </div>
  <button type="button" (click)="addNext()">Add Next</button>
  <button type="submit">Submit</button>
</form>

您可以创建带有扩展项目集的表单.

And you can create form with expanding set of items.

这篇关于动态地将一组字段添加到反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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