选中复选框时,角反应式表单将禁用输入 [英] Angular reactive forms disable input when checkbox checked

查看:85
本文介绍了选中复选框时,角反应式表单将禁用输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复选框并输入.我要做的是在选中复选框时禁用输入,而在取消选中复选框时启用输入.

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的值更改时,您可以对模型执行任何操作.例如,您可以同时

reset()和 disable() FormControl,或者检查是否满足某些条件.

You will have to find the appropriate place in your code start the subscription. With this you can do whatever you like to the model when the value of the toggle FormControl changes. You can for example reset() and disable() the FormControl at the same time, or check if certain conditions are met.

这篇关于选中复选框时,角反应式表单将禁用输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆