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

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

问题描述

我有一个复选框和输入.我想要做的是在复选框被选中时禁用输入,并在复选框未选中时启用输入.

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 属性指示.如果在设置此控件时将 disabled 设置为 true您的组件类,禁用属性实际上将被设置在给你的 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方法省略的observable:

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.

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

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