角反应式表单将禁用输入

角反应式表单将禁用输入

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

问题描述

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

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:

我不能使用

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.

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

08-24 19:31