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.
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.
The solution is to use [attr. disabled].
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>
It works fine like this [attr.disabled]="isDisabledState === true"
And in the component class you can have isDisabledState: boolean = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With