angular - 如何使用反应形式创建动态角度形式?
问题描述
我需要使用角度反应创建一个动态表单。但是这有很多子表单组,这些组可能会根据表单选择框的值而改变。
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
department: new FormControl('')
});
部门类型是'a', 'b', 'c'
.
如果用户选择'a'
,我将添加一个名为"departmentSettings"
profileForm的新 FormGroup
aFormGroup = new FormGroup({
xWorkTime: new FormControl(''),
yWorkTime: new FormControl('')
})
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
department: new FormControl(''),
departmentSettings: new FormGroup({
xWorkTime: new FormControl(''),
yWorkTime: new FormControl('')
})
});
如果用户选择'b'
,我将FormGroup
在 profileForm 中添加一个新的
bFormGroup = new FormGroup({
someProperty: new FormControl(''),
otherProperty: new FormControl('')
})
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
department: new FormControl(''),
departmentSettings: new FormGroup({
someProperty: new FormControl(''),
otherProperty: new FormControl('')
})
});
其他情况是这样的。那么我怎么能用简单的角度来做到这一点呢?
解决方案
在您的 html 中,将 (change)='someFunction()' 属性添加到部门输入。
<input matInput type="select" #departmentInput formControlName="department"
(change)="doChange($event)">
当输入的值发生变化时,这将触发该函数,然后您可以将新的表单控件添加到您的反应式表单。
反应式表单有一个 FormGroup.addControl() 方法可以做到这一点。 https://angular.io/api/forms/FormGroup
推荐阅读
- javascript - 替换所有不在Javascript中方括号之间的字母
- javascript - Botium If Else 条件类似于 Alexa 响应的语句
- oop - 聚合关系C ++中另一个类中的一个类的静态对象
- bash - bash:简单和大数组上的巨大循环,最后一个元素上的错误+内存泄漏
- java - 如何使 recyclerview 根据百分比只显示一个数组?
- c# - 每个属性的 GroupBy Lamda 表达式构建器
- python - 将列表中的一组不同参数传递给函数
- r - rvest 抓取不完整的 html 表
- node.js - puppeteer 设置“isMobile:true”导致“UnhandledPromiseRejectionWarning”
- python-3.x - MlpLnLstmPolicyin 稳定基线的默认架构是什么?