Angular reactive forms disable input when checkbox checked

不羁的心 提交于 2021-02-07 20:15:40

问题


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 is my form group:

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'); }

I was sure this will work:

<input [disabled]="toggleControl.value">

But I'm getting a warning in the console:

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.

I can't use

from: [{ value: null, disabled: this.toggleControl.value }]

Because toggleControl is not yet accessible.

Any ideas? Thanks


回答1:


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()
  }
}

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.



来源:https://stackoverflow.com/questions/50369523/angular-reactive-forms-disable-input-when-checkbox-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!