您面临的问题与一个角度错误有关,您可以找到更多信息here。
有一些对我有用的解决方法:
- 在 setTimeout 中调用禁用函数。
validateCheckboxSelectionAndChangeInputState() {
if (!this.cb1.value && !this.cb2.value) {
this.isCheckboxSelectionInvalid = true;
setTimeout(() => {
this.inputBox.disable();
}, 0);
} else {
this.isCheckboxSelectionInvalid = false;
this.inputBox.enable();
}
}
- 直接设置disabled属性:
<input type="text" [attr.disabled]="form.controls['inputBox'].disabled" formControlName="inputBox" />
- 在调用启用/禁用函数之前调用 detectChanges。
validateCheckboxSelectionAndChangeInputState() {
this.ref.detectChanges();
if (!this.cb1.value && !this.cb2.value) {
this.isCheckboxSelectionInvalid = true;
this.inputBox.disable();
} else {
this.isCheckboxSelectionInvalid = false;
this.inputBox.enable();
}
}
与问题无关的建议:
有启用或禁用控件的想法,可以订阅表单valueChanges:
initForm() {
this.form = this.formService.getForm();
this.cb1 = this.form.get("cb1");
this.cb2 = this.form.get("cb2");
this.inputBox = this.form.get("inputBox");
this.form.valueChanges.subscribe(
this.validateCheckboxSelectionAndChangeInputState.bind(this)
);
}
validateCheckboxSelectionAndChangeInputState(controls) {
if (this.inputBox.disabled && controls.cb1 && controls.cb2) {
this.inputBox.enable();
}
if(this.inputBox.enabled && !controls.cb1 && !controls.cb) {
setTimeout(() => {
this.inputBox.disable();
}, 0);
}
}
toggleCb1() {
this.cb1.setValue(!this.cb1.value);
}
toggleCb2() {
this.cb2.setValue(!this.cb2.value);
}
resetForm() {
this.initForm();
}
您还可以使用 form.valid 并使用 Validators.requiredTrue [禁用] 按钮:
html
<button [disabled]="!form.valid" (click)="submitForm()">
Submit
</button>
ts
public getForm() {
return this.fb.group({
cb1: this.fb.control(false, [Validators.requiredTrue]),
cb2: this.fb.control(false, [Validators.requiredTrue]),
inputBox: this.fb.control(
{ value: "", disabled: true },
[Validators.required]
)
});
}
见https://stackblitz.com/edit/angular-6-reactive-form-disable-jn4cf8?file=src%2Fapp%2Fapp.component.ts