简体   繁体   English

在 Angular 中构建动态 FormBuilder

[英]Build Dynamic FormBuilder in Angular

I have created an Angular project with Dynamic Inputs, I click on a button then new inputs create and I want to use FormBuilder to get the data but I don't know how to do this.我创建了一个带有动态输入的 Angular 项目,我单击一个按钮然后创建新输入,我想使用 FormBuilder 获取数据但我不知道如何执行此操作。

I know how to use FormBuilder in the static case but I didn't find any resource for dynamic.我知道如何在 static 案例中使用 FormBuilder,但我没有找到任何动态资源。

Which are the steps to follow to achieve that?实现该目标应遵循哪些步骤?

How are you adding new inputs to the existing formgroup?您如何向现有表单组添加新输入? For example you can do this by using form arrays, and basically with that you are able to gate de value from it just by accessing like: formGroup.get("formArray").value -> you will get all the inputs value by one shot.例如,您可以使用表单 arrays 来执行此操作,基本上您可以通过访问以下方式从中获取价值: formGroup.get("formArray").value -> 您将通过一个获得所有输入值射击。

Im not too sure if this is what you meant but if you wanted to add new inputs everytime user clicks button and get the value then you could try this.我不太确定这是否是你的意思,但如果你想在每次用户单击按钮时添加新输入并获取值,那么你可以试试这个。 expanding on @ZsoltB answer working stackblitz link扩展@ZsoltB 回答工作stackblitz 链接

@Component({
  ...all the decorator things
})
export class AppComponent {
  formArray = new FormArray([
    new FormGroup({
      firstName: new FormControl(''),
      lastName: new FormControl(''),
    }),
  ]);
  name = 'angular';

  addNewInput = () => {
    this.formArray.push(
      new FormGroup({
        firstName: new FormControl(''),
        lastName: new FormControl(''),
      })
    );
  };
}

I solved the problem by using and inspired by the following code:我通过使用以下代码并受到以下代码的启发解决了这个问题:

dynamic form in angular, add fields on runtime angular 中的动态表单,在运行时添加字段

thank you very much非常感谢你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM