I am working on angular material 2 radio button following this documentation:https://material.angular.io/components/component/radio.
The problem that I am facing is to have the radio button a default selected value of No
. If you see in the plunker:https://plnkr.co/edit/jdRxVLdSfFqR4XOdpyUN?p=preview you will find that none of the options are selected. I would want the default value to be No
when the page loads.
To work with Angular Material radio button we need to import MatRadioModule in application module. Angular provides MatRadioGroup to group radio buttons. The selector of MatRadioGroup is mat-radio-group . Radio button is created using MatRadioButton and its selector is mat-radio-button .
You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .
Reasons for A Default Selection Give people control and align with their expectations (Good): It is better to have a selected radio button by default, given that people cannot deselect and set the button back to its original state once one has been selected. A default selection sets the correct user expectation.
A lot of the plunkrs don't seem to work for me anymore. There's a modified stackblitz here:
Blitz
As mentioned we can either set the ngModel and the variable:
[(ngModel)]="favoriteSeason"
and in the 'ts' file:
favoriteSeason: string = 'Winter';
Or we can set the checked:
[checked]="season === 'Winter'"
Another little gotcha I've discovered recently is that if you mistakenly give mat-checkbox incorrect (duplicate IDs), then it does not work - you cannot check anything. Ensure your IDs are unique.
You can use checked
, like so:
[checked]="data.value ==='false'"
notice that we are checking using string 'false'
, instead of false
, as your value has the string with value false
.
Plunker
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