5

I understand how we can specify the initial state of a reactive form control to be disabled.

someControl: [{value: '', disabled: true}]

How can I change the disable state at a later time, programmatically, based on a selection of another value in the form. So, e.g. someControl should be disabled if anotherControl has a certain value selected in a dropdown and enabled otherwise.

Thanks

2 Answers 2

17

You can watch for valueChanges with your select field, here's an example with a form with a dropdown and an input field that we will disable/enable based on value chosen from dropdown:

this.myForm = this.fb.group({
  selects: [''],
  inputField: ['']
})

  // subscribe to changes in select field, if the value chosen is "two", 
  // disable input field, else enable field
  this.myForm.get('selects').valueChanges.subscribe(val => {
    if(val === 'two') {
      this.myForm.get('inputField').disable()
    }
    else {
      this.myForm.get('inputField').enable()
    }
  })

Here's a

DEMO


EDIT:

As developer033 suggested, you can also use simple change event, where template...

<select formControlName="selects" (change)="checkValue()">
  <option disabled></option>
  <option *ngFor="let a of arr">{{a}}</option>
</select>

and component would be:

checkValue() {
  if(this.myForm.get('selects').value === 'two') {
    this.myForm.get('inputField').disable()
  }
  else {
    this.myForm.get('inputField').enable()
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This should be the accepted answer :) But, instead of subscribing to the valueChanges, I'd prefer to use (change) event on select.
:) Yeah, I figured first that I would do it with change event, but thought that since we are dealing with a model-driven form, leeeet's go with valueChanges, but yes, you are absolutely right, might even just be wiser to use change event ;)
Thank you for the answer. This answer definitely provides more details. I think both answers are helpful. I will upvote this one.
No problem, you decide what answer to accept :) Have a good one and happy coding! :)
5

this should work

this.someControl.reset({value: '', disabled: true});

1 Comment

Is There are reason , this answer was down voted? Please share if have a valid reason . I will try to improve the answer in future.

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.