nircraft
nircraft

Reputation: 8468

Disable a radio button conditionally in a radio button group inside Reactive form in Angular 4+

I have a reactive form created in component and some formControls defined on it.

Now i need to disable one of the radio button from a radio button group based on some condition.

How do i do it while creating formControl?

PFB the code snippet:

createForm() {
this.heroForm = this.fb.group({
  confirmActionRadioGrp: this.fb.group({
            updateAction: new FormControl({ value: '' })
        })

  });
}

inside my template:

    <div class="form-group confirm-action-radio-container" formGroupName="confirmActionRadioGrp">
<input  type="radio"  class="custom-control-input" value="1" formControlName="updateAction">
    <input  type="radio"  class="custom-control-input" value="2" formControlName="updateAction">
    <input  type="radio"  class="custom-control-input" value="3" formControlName="updateAction"></div>

Now how to disable one of them conditionally? when using [disable] attribute i get some warning in browser console. Angular doesn't encourage doing it

Upvotes: 7

Views: 20055

Answers (3)

Markus Pscheidt
Markus Pscheidt

Reputation: 7331

Embedding the radio button with a fieldset is a further option to disable that particular radio button:

<div class="form-group confirm-action-radio-container" formGroupName="confirmActionRadioGrp">
    <fieldset [disabled]="myDisabledCondition || null">
        <input  type="radio"  class="custom-control-input" value="1" formControlName="updateAction"
    </fieldset>
    <input  type="radio"  class="custom-control-input" value="2" formControlName="updateAction">
    <input  type="radio"  class="custom-control-input" value="3" formControlName="updateAction">
</div>

See also https://stackblitz.com/edit/angular-radio-bug

Upvotes: 1

RockGuitarist1
RockGuitarist1

Reputation: 716

For Reactive Form controls, you should set disabled either when the form is being made, or later on. This is how you do both:

this.heroForm = this.fb.group({
    updateAction: [{ value: null, disabled: true }]
});

or

this.heroForm.get('updateAction').disable();

Otherwise, if you don't want to disable a Reactive Form control, you will use [disabled]="".

Upvotes: 4

bryan60
bryan60

Reputation: 29305

Ignore the browser warning and use the disabled attribute on the input. If you'd like you can use :

[attr.disabled]="whatever"

instead which should silence the warning. Angular reactive forms do not currently support disabling individual radio buttons in a group through the formcontrol / formgroup API as per this open issue:

https://github.com/angular/angular/issues/11763

Upvotes: 12

Related Questions