Angular 中如何对一个动态表单根据 select 的选项 disable 关联的 input?
# 代码
基本思路是使用statusChanges
监测 form 的 select 控件值,当值发生变化时,对关联值调用disable()
方法使能或禁用。
createForm() {
const controlsConfig = {};
_.forEach(this.moduleOptions, (moduleOption) => {
controlsConfig[moduleOption.name] = [
moduleOption.default_value,
this.getValidators(moduleOption),
];
});
this.ipmiModuleForm = this.formBuilder.group(controlsConfig);
// see also:
// 1. https://stackoverflow.com/questions/39681674/use-disable-with-model-driven-form
// 2. https://stackoverflow.com/questions/45412773/how-to-disable-all-formcontrols-inside-a-formgroup
let modelControl = this.ipmiModuleForm.get('model')
let ipControl = this.ipmiModuleForm.get('ip_addr')
let maskControl = this.ipmiModuleForm.get('netmask')
let gwControl = this.ipmiModuleForm.get('gateway')
modelControl.statusChanges.subscribe((newStatus) => {
if (modelControl.value !='dhcp') {
// 如果网络模式改为dhcp,则配置项全disable,否则enable
ipControl.enable();
maskControl.enable();
gwControl.enable();
} else {
ipControl.disable();
maskControl.disable();
gwControl.disable();
}
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 效果
# 参考链接
编辑 (opens new window)
上次更新: 2024-07-15, 03:27:09