【问题标题】:How to append a formgroup to another?如何将表单组附加到另​​一个?
【发布时间】:2019-02-11 10:33:40
【问题描述】:

我有两个表单组:firstFormGroupsecondFormGroup

firstFormGroup 在垫子步骤 1 中,secondFormGroup 在垫子步骤 2 中。 现在在将其发布到后端时,我想将secondFormGroup 附加到firstFormGroup

如何做到这一点?

【问题讨论】:

  • 当您在这里提出问题时,您必须提供一些代码的 sn-ps,以便其他人能够得到想法并给出解决方案。
  • 如您所知,formGroup 只不过是一对键:值。因此,您可以轻松地将两个对象合并为一个对象,例如 Object.assign({},firstFormGroup.value,secondFormGroup.value);

标签: angular forms angular6 formgroups


【解决方案1】:

您可以从这些表单中获取值并使用Object.assign 将它们合并到一个字典中。

const data = Object.assign({}, firstFormGroup.value, secondFormFroup.value);

另外,您可以使用嵌套表单组

export class MyComponent implements OnInit {

  form = new FormGroup({
    first: new FormGroup({
      name: new FormControl('')
    }),
    second: new FormGroup({
      name: new FormControl('')
    })
  });
  constructor() { }

  ngOnInit() {
  }

}

然后在模板中

<form [formGroup]="form.get('first')"></form>
<form [formGroup]="form.get('second')"></form>

这样,即使您在多个步骤中使用相同键的控件并且只有一个表单可以使用和验证,您也不会丢失任何数据。

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2010-10-25
    • 2020-10-06
    • 2020-02-02
    相关资源
    最近更新 更多