3

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>

1 Answer 1

7

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:

FormControl({ value: '', disabled: true })

and then add an "enabler" on the radio button control like this:

this.myForm.get('myRadio').valueChanges.subscribe(value => {
    const enableOrDisable = value !== null ? 'enable' : 'disable';
    this.myForm.get('myInput')[enableOrDisable]();
});

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.

<input matInput formControlName="myInput" [disabled]="!myForm.value?.myRadio" />

Then initialize the value of your myRadio in your form to null. If you set your radio values instead to true and false instead of yes and no, then you'd just have to check against a null value (myForm.value?.myRadio !== null).

2
  • the this.myForm.get('myRadio').valueChanges where it should be called in the component ? Aug 31, 2021 at 8:55
  • I would do this right after you initialize your form. I often call a buildForm() method within my ngOnInit(). In there, you can create the form and then subscribe to the changes. Make sure to unsubscribe too on destroy
    – Scrimothy
    Sep 1, 2021 at 11:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.