Angular: 如何将多个表单控件附加到表单组

Angular: How to append multiple form controls to form group

我使用的是最新版本的 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(''));
}

如果您不想延迟表单创建,您可以简单地执行以下操作:

// You can write this sugar, you don't have to write new FormControl
const form = {
    id: ['', Validators.required],
    firstName: ['', Validators.required],
    lastName: ['', Validators.required]
};

if (blah) {
    form.someField: ['', Validators.required];
} else {
    form.someotherField: ['', Validators.required];
}

this.form = this.formBuilder.group(form);

或者这个较短的内联版本:

this.form = this.formBuilder.group({
    id: ['', Validators.required],
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    ...(blah ? {form.someField: ['', Validators.required]} : {form.someotherField: ['', Validators.required]})
});

出于某种原因 Angular didn't provide API 对于这种情况。

您可以简单地遍历您的控件并将其添加到 FormGroup,或者您可以基于现有的 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-run Example