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

Issue

I got this problem in my angular app. I have many options in a mat-radio-group but these are dynamically placed according to a json object. Something like this:

This is the json object

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

in this example there are just two objects in my list, but could be 9, 20 or any number of objects.

So I want that in my html is that no matter how many objects are, only the first one is selected, even if the list change just the first object stay selected.

This is my html:

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

the listOfOptions variable have the JSON object.

How do I always set selected the first object?

Solution

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>

Answered By – filipbarak

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published