6

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

2
  • Take a look at this answer. Commented May 16, 2018 at 11:22
  • you could use workingTime.values.toggle. Maybe toggleControl().value? Commented May 16, 2018 at 11:34

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Have you created a new account just to answer me? Thanks I will try it now.
@Thomas R. Just a detail: Add a closing brace and and some semicolons to your suggested code. ;)
Any ideas why when I disabled the field get removed from the object reF: stackoverflow.com/questions/74491543/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.