I have a 'mat-radio-group' in my form which has 2 'mat-radio-button's with values "yes" and "no".
I want to use these values to enable or disable another input field (simple matInput) depending on what the user selects.
I would also like to disable the matInput by default (before the user check "yes" or "no" from the radio group).
I'm using Angular reactive forms and have setup form control names for these inputs.
Imagine the formGroup name is "myForm".
Below is the code I have in my template:
<mat-radio-group formControlName="myRadio">
<mat-radio-button value="yes" required>Yes</mat-radio-button>
<mat-radio-button value="no" required checked>No</mat-radio-button>
</mat-radio-group>
<mat-form-field>
<input matInput formControlName="myInput" />
</mat-form-field>
Best Answer
Updated for preferred Reactive way
Thanks to @Severus' comment, I wanted to update my answer to reflect the preferred way of handling this on reactive forms. My original answer below was the "quick and dirty" way, but if you want to do this properly, you should initialize your
myInput
to disabled in the form creation:and then add an "enabler" on the radio button control like this:
Original Answer
Note: This approach is still valid when using a template-driven form, but should not be used in a reactive form methodology. If using in template forms, you'd just set the disabled value to the
ngModel
bound to the radio button.You should just be able to set disabled to the value of the dependent field.
Then initialize the value of your
myRadio
in your form tonull
. If you set your radio values instead totrue
andfalse
instead ofyes
andno
, then you'd just have to check against anull
value (myForm.value?.myRadio !== null
).