Angular 选中复选框时反应式表单禁用输入

Angular reactive forms disable input when checkbox checked

我有一个复选框和输入框。我想做的是当复选框被选中时禁用输入,当复选框未选中时启用输入。

这是我的表格组:

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">

但我在控制台中收到警告:

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 还不能访问。

有什么想法吗?谢谢

您可以订阅FormControl的valueChanges方法省略的observable:

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,或者检查是否满足某些条件。