前言

书接上回,我们在上文中将表单展示出来了,但是怎么按照逻辑对表单进行限制呢?比如说基本的禁用表单中的某个字段?

方法

直接使用disable=true并不能随着 checkbox 的变化使值变化,所以我们需要这么写:

<!--html-->
<!-- Field control -->
<!-- bool -->
<div class="form-group"
*ngIf="moduleOption.value.type === 'bool'">
<div class="checkbox checkbox-primary">
<input id="{{ moduleOption.value.name }}"
type="checkbox"
(change)="onUserCheckMode()"
formControlName="{{ moduleOption.value.name }}">
<label i18n for="{{ moduleOption.value.name }}"> Check set mode auto/manual.</label>
</div>
</div>

// xx.ts
//在选择time时,如果自动,则disable部分input
onUserCheckMode() {
this.isAuto = this.sysSettingForm.value.auto == true;
if (this.isTime) {
if (this.isAuto == true) {
this.sysSettingForm.get('ntp_addr').enable();
this.sysSettingForm.get('date').disable();
this.sysSettingForm.get('time').disable();
this.sysSettingForm.get('time_zone').disable();
} else {
this.sysSettingForm.get('ntp_addr').disable();
this.sysSettingForm.get('date').enable();
this.sysSettingForm.get('time').enable();
this.sysSettingForm.get('time_zone').enable();
}
}
}

// 初始化表格时,对表格也需要disable
createForm() {
const controlsConfig = {};
_.forEach(this.moduleOptions, (moduleOption) => {
switch (moduleOption.type) {
case 'bool':
controlsConfig[moduleOption.name] = [this.isAuto, this.getValidators(moduleOption)];
break;
default:
controlsConfig[moduleOption.name] = [moduleOption.default_value, this.getValidators(moduleOption)];

}
});
this.sysSettingForm = this.formBuilder.group(controlsConfig);
if (this.isTime) {
if (this.isAuto == true) {
this.sysSettingForm.get('ntp_addr').enable();
this.sysSettingForm.get('date').disable();
this.sysSettingForm.get('time').disable();
this.sysSettingForm.get('time_zone').disable();
} else {
this.sysSettingForm.get('ntp_addr').disable();
this.sysSettingForm.get('date').enable();
this.sysSettingForm.get('time').enable();
this.sysSettingForm.get('time_zone').enable();
}
}
}

效果

根据选择框disable/enable

参考

angular - Disable Input fields in reactive form - Stack Overflow