JCP
JCP

Reputation: 189

Trying to set a default mat-radio-button

I attempting to set a default checked box (value 100) if no button has been selected by the user/ or if the user does not explicitly select a checkbox. Please see my current implementation:

<div class="col-md-5">
    <mat-radio-group #radioGroup="matRadioGroup" (change)="radioChange($event)" [(ngModel)]="queueManageBean.resReturn">
        <mat-radio-button
                    value="10" [checked]="10 == queueManageBean.resReturn">10</mat-radio-button>
        <mat-radio-button value="25" style="margin-left: 15px;"
                [checked]="25 == queueManageBean.resReturn">25</mat-radio-button>
        <mat-radio-button value="100" style="margin-left: 15px;"
                [checked]="100 == queueManageBean.resReturn">100</mat-radio-button>
        <mat-radio-button value="250" style="margin-left: 15px;"
                [checked]="250 == queueManageBean.resReturn">250</mat-radio-button>
        <mat-radio-button value="500" style="margin-left: 15px;"
                [checked]="500 == queueManageBean.resReturn">500</mat-radio-button>
    </mat-radio-group>
</div>

The queueManageBean.resReturn is retrieved from ts

queueManageBean = new queueManageBean;
resReturn:number;
this.queueManageBean.resReturn = this.resReturn;

Even if I explicitly set value 100 to 'true', it still is not the default value. Any idea?

Upvotes: 1

Views: 84

Answers (1)

Andrew Halil
Andrew Halil

Reputation: 1323

In your HTML, the default value is set as a string, and your conditions use a == equality operator so strings should match, but the type for the resReturn property needs to match that of the values in the radio button's value attribute and the checked attribute condition is comparing string types.

When the bound property queueManageBean.resReturn changes, and the checked attribute evaluates to true, the corresponding radio button will be selected.

In the TS code, you can set the default to a value as shown:

queueManageBean = new queueManageBean();
resReturn: number = 100;

constructor() {
  this.queueManageBean = new queueManageBean();
  this.queueManageBean.resReturn = this.resReturn.toString();
}

Define your class as shown to hold the resReturn property:

export class queueManageBean {
    resReturn: string;
} 

The above will set the default to 100 for the radio button.

Upvotes: 1

Related Questions