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

时间:2018-06-18 10:19:19

标签: angular angular-forms

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

2 个答案:

答案 0 :(得分:4)

出于某种原因Angular didn't provide 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-run Example

答案 1 :(得分:2)

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

// 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]})
});