angular - 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(''));
}
解决方案
出于某种原因,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('')
});
}
推荐阅读
- excel - 需要简化公式以在添加工作表时自动更新
- c# - 如何从不同的表 C# 中引用图像
- reactjs - React 渲染缺少分号
- raspberry-pi - 更换 mcc 帽子导致测量错误
- flutter - Flutter 中的响应式容器
- javascript - 如何通过javascript中的单元格内容删除行?
- python - Cron 作业在气流中的错误日期运行
- data-science - 数据科学项目中关于预测房价的数据选择
- javascript - 我正在尝试添加仅显示在某个部分的评论区,但出现错误:无法读取 null 的属性“addEventListener”
- python - 如何在导入中模拟导入