Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular reactive forms disable input when checkbox checked

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

like image 932
Rafff Avatar asked Aug 31 '26 10:08

Rafff


1 Answers

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.

like image 62
Thomas R. Avatar answered Sep 03 '26 06:09

Thomas R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!