Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 855
Sergio Mendez Avatar asked Feb 27 '18 16:02

Sergio Mendez


2 Answers

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>
like image 89
filipbarak Avatar answered Nov 16 '22 07:11

filipbarak


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;
like image 16
Alexander Shershakov Avatar answered Nov 16 '22 07:11

Alexander Shershakov