Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - Disabling Radio Buttons

I have a radio button group in Angular 5. I want to disable some options, using the [disabled] attribute. However, I am noticing only the first radio button actually gets disabled. See my plunker: http://plnkr.co/edit/JzFmvjUyvhPdTkbYT1YZ?p=preview

Even if I hard code [disabled]="true", it still doesn't disable the second radio button. I don't want to switch to using a <select>, so I am curious if there is another way to get this to work with radio buttons.

like image 936
Travis Parks Avatar asked Nov 21 '17 18:11

Travis Parks


People also ask

How to disable Mat radio button in Angular?

We can also disable the radio button by using the disabled input property. If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.

How to disable p radio button in Angular?

The solution is to use [attr. disabled].


2 Answers

There can be 2 solutions for this :-

1. Using the disabled attribute ([attr.disabled])

One solution to this problem can be using the disabled attribute ([attr.disabled]) instead of the disabled property ([disabled]), but [attr.disabled] works slightly differently, to enable the radio button you need to pass null to [attr.disabled] and any non-null value to disable it. Consider the below example :-

<input type="radio" name="enabled" [attr.disabled]="null" />Enabled1
<input type="radio" name="enabled" [attr.disabled]="null" />Enabled2

<input type="radio" name="disabled" [attr.disabled]="false" />Disabled1
<input type="radio" name="disabled" [attr.disabled]="false" />Disabled2

In this example the set of radio buttons named "enabled" will be enabled since for them [attr.disabled] is set to null, whereas the set of radio buttons named "disabled" will be disabled despite the [attr.disabled] being set to "false" this is because false is a non-null value.

2. Using fieldset tag

Another even better solution for this problem is using the <fieldset> tag for grouping the radio buttons together and then setting the [disabled] property on that <fieldset> tag instead of individual radio buttons. Below is an example for the same :-

<fieldset [disabled]=true>
    <input type="radio" name="test" />yes
    <input type="radio" name="test" />no
</fieldset>
like image 163
Yatharth Varshney Avatar answered Sep 18 '22 12:09

Yatharth Varshney


It works fine like this [attr.disabled]="isDisabledState === true"

And in the component class you can have isDisabledState: boolean = true

like image 44
DrNio Avatar answered Sep 22 '22 12:09

DrNio