Set mat-radio-button default selected in a mat-radio-group with angular2 Set mat-radio-button default selected in a mat-radio-group with angular2 angular angular

Set mat-radio-button default selected in a mat-radio-group with angular2


Add a checked property in the JSON

{  "list": [    {"name": "some name 1", ID: "D1", "checked": true},    {"name": "some name 2", ID: "D2", "checked": false}  ]}

and then

    <mat-radio-group name="opList"  fxLayout="column">      <mat-radio-button *ngFor="let op of listOfOptions"       [checked]="op.checked" name="opList" >{{ op.name}}</mat-radio-button>    </mat-radio-group>


Use [value]="op.name" and make a binding to your Component variable like [(ngModel)]="chosenItem"

HTML:

<mat-radio-group name="opList"  fxLayout="column" [(ngModel)]="chosenItem">      <mat-radio-button *ngFor="let op of list" [value]="op.name" name="opList" >{{ op.name}}</mat-radio-button>  </mat-radio-group>

In your Component:

list = [    { "name": "some name 1", ID: "D1"},    { "name": "some name 2", ID: "D2"}]chosenItem = this.list[0].name;


Add let i = index to the *ngFor, then hook [value] and [checked] to it.

<mat-radio-group>  <mat-radio-button *ngFor="let o of options; let i = index" [value]="i" [checked]="i === 0"><mat-radio-group>

This will check the very first radio button.