选中复选框时,角反应式表单将禁用输入 [英] Angular reactive forms disable input when checkbox checked
问题描述
我有一个复选框并输入.我要做的是在选中复选框时禁用输入,而在取消选中复选框时启用输入.
I have a checkbox and input. What I want to do is to disable the input when the checkbox is checked, and enable the input when the checkbox is unchecked.
这是我的表单组:
this.workingTime = this.fb.group({
toggle: false, // this is the checkbox
from: [{ value: null, disabled: false }],
to: [{ value: null, disabled: false }]
});
get toggleControl() { return this.workingTime.get('toggle'); }
我确定这会起作用:
<input [disabled]="toggleControl.value">
但是我在控制台中收到警告:
But I'm getting a warning in the console:
您似乎正在使用带有反应形式的Disabled属性指示.如果您在您的组件类,disable属性实际上将在您的DOM.我们建议您使用这种方法来避免更改经过检查后的错误.
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors.
我不能使用
from: [{ value: null, disabled: this.toggleControl.value }]
因为toggleControl尚不可用.
Because toggleControl is not yet accessible.
有什么想法吗?谢谢
推荐答案
您可以订阅FormControl的valueChanges方法忽略的可观察对象:
You can subscribe to the observable omitted by the valueChanges method of the FormControl:
this.workingTime.get('toggle').valueChanges.subscribe(v => {
if (v) {
this.workingTime.get('from').disable()
this.workingTime.get('to').disable()
} else {
this.workingTime.get('from').enable()
this.workingTime.get('to').enable()
}
}
您必须在代码中找到合适的位置才能开始订阅.这样,当切换FormControl的值更改时,您可以对模型执行任何操作.例如,您可以同时