本文介绍了角度6:如何使用FormGroup动态创建formControlName?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样的formControlName

I want formControlName Like this,

  • field_0
  • field_1
  • field_2

myObj = { "field_0":"value_0", "field_1":"value_1", "field_2":"value_2", }}

myObj = { "field_0":"value_0", "field_1":"value_1", "field_2":"value_2", }}

推荐答案

如果您喜欢的话

fields=["field_0","field_1","field_2"]

您首先必须创建一个FormGroup

You first must create a FormGroup

  createForm(fields: string[]) {
    let group: any = {};
    fields.forEach(x => {
      group[x] = new FormControl();
    })
    return new FormGroup(group);
  }

而且,当您想要显示它时

And, when you want show it

<form [formGroup]="form">
  <div *ngFor="let field of fields">
    <input [formControlName]="field">
  </div>
</form>
{{form?.value|json}}

好吧,我们可以用带有标签," field," value的对象数组替换字段以创建表单

Well, we can replace fields by an array of objects with label","field","value" to create the form

请参见 stackblitz

这篇关于角度6:如何使用FormGroup动态创建formControlName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:53