Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default radio button select value angular material 2

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.

like image 592
Aakash Thakur Avatar asked May 09 '17 11:05

Aakash Thakur


People also ask

How to select the radio button in Angular Material?

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 .

How can I change the default value of 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> .

Should radio button have default value?

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.


2 Answers

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.

like image 173
PeterS Avatar answered Sep 20 '22 08:09

PeterS


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

like image 37
AT82 Avatar answered Sep 18 '22 08:09

AT82