首页 > 解决方案 > Angular:如何将多个表单控件附加到表单组

问题描述

我正在使用最新版本的 Angular (v6.0.5)。

我有一个由 3 个通用控件组成的 FormGroup,并且基于某些逻辑,我想将其他多个控件添加到同一个 FormGroup。

我知道我可以使用this.form.addControl(),但我不想为每个单独的表单控件执行此操作

是否有捷径可寻?

例子:

this.form = this.formBuilder.group({
    'id': new FormControl('', Validators.required),
    'firstName' new FormControl('', Validators.required),
    'lastName' new FormControl('', Validators.required)
});

if (blah) {
    // Append more FormControls here to same FormGroup
    this.form.addControl('houseNumber', new FormControl(''));
    this.form.addControl('street', new FormControl(''));
    this.form.addControl('postCode', new FormControl(''));
}

标签: angularangular-forms

解决方案


出于某种原因,Angular没有为这种情况提供 API。

您可以简单地循环您的控件并将其添加到 FormGroup 或者您可以基于现有的构建新的 FormGroup:

this.form = this.formBuilder.group({
  'id': new FormControl('', Validators.required),
  'firstName': new FormControl('', Validators.required),
  'lastName': new FormControl('', Validators.required)
});

let blah = true;

if (blah) {
  this.form = this.formBuilder.group({
    ...this.form.controls,
    'houseNumber': new FormControl(''),
    'street': new FormControl('')
  });
} else {
  this.form = this.formBuilder.group({
    ...this.form.controls,
    'otherControl': new FormControl(''),
    'otherControl2': new FormControl(''),
    'otherControl3': new FormControl('')
  });
}

Ng 运行示例


推荐阅读