37

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?

Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
Sergio Mendez
  • 1,311
  • 8
  • 33
  • 56

8 Answers8

44

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>
filipbarak
  • 1,835
  • 2
  • 17
  • 28
  • 1
    The above doesn't work in this stackblitz. https://stackblitz.com/edit/angular-wczrjt?file=src%2Fapp%2Fapp.component.ts Getting this error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'mat-radio-checked: true'. Current value: 'mat-radio-checked: false'." – Erik Ostermueller Mar 26 '19 at 03:41
  • That does not work. I changed checked property to true for the first button, but selection did not change. – Mark Apr 22 '23 at 10:33
21

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;
  • This is the right answer. In angular the checked/selected item is decided by the value it equals to. In this case set the value in component (model) the desired value to the ngmodel binded variable. – Vijay Kumar Kanta May 20 '19 at 13:33
21

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.

Csaba
  • 1,945
  • 3
  • 28
  • 46
8

Use checked attribute as true to set the radio button selected as default.

Example:

<mat-radio-group>
     <mat-radio-button [checked]="true"> Yes </mat-radio-button>
     <mat-radio-button> No </mat-radio-button>
</mat-radio-group>
Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
6

You can use [checked]='true' with first radio button in HTML.

If you want to change checked value so you can also set it dynamically.

 <mat-radio-group >
     <mat-radio-button [checked]='true'>yes </mat-radio-button>
</mat-radio-group>
sharad jain
  • 1,471
  • 13
  • 9
4

For those who are still looking for the right answer, I would follow the documentation: here with one little addition at ngOnInit():

and it goes - TS:

import {Component, OnInit} from '@angular/core';


@Component({
  selector: 'radio-btns-test',
  templateUrl: 'radio-btns-test.html',
  styleUrls: ['radio-btns-test.css'],
})
export class RadioBtnsTest implements OnInit {
                             // data source for the radio buttons:
  seasons: string[] = ['Winter', 'Spring', 'Summer', 'Autumn'];

                             // selected item
  favoriteSeason: string;

                             // to dynamically (by code) select item
                             // from the calling component add:
  @Input() selectSeason: string;



  ngOnInit() {
                             // To have a default radio button checked
                             // at the page loading time (fixed solution)
      this.favoriteSeason = 'Summer';

                             // OR  (do only one)
                             // To dynamically (by code) select item
                             // from the calling component add:
      this.favoriteSeason = this.selectSeason;
  }

}

HTML:

<label id="example-radio-group-label">Pick your favorite season</label>

<mat-radio-group
  aria-labelledby="example-radio-group-label"
  class="example-radio-group"
  [(ngModel)]="favoriteSeason">

  <mat-radio-button 
       class="example-radio-button" 
       *ngFor="let season of seasons" 
       [value]="season">
    {{season}}
  </mat-radio-button>

</mat-radio-group>

<div>Your favorite season is: {{favoriteSeason}}</div>

CSS

.example-radio-group {
  display: flex;
  flex-direction: column;
  margin: 15px 0;
}

.example-radio-button {
  margin: 5px;
}

For completion of the example - with initiation of the radio-btn-test from another component call it like this:

<radio-btns-test [selectSeason]="'Summer'"></radio-btns-test>
Felix
  • 1,662
  • 2
  • 18
  • 37
  • it gave me a guideline. I was using a number as a value but it did not work. I changed it to a string and it worked. thanks – MindRoasterMir Oct 19 '21 at 13:55
2

I had this problem too. I was using angular material 7 and I tried with [checked]="i==0" but for some reason, it did not work. I also tried adding a new boolean field to my JSON object named isDefault, and then using [checked]="obj.isDefault" with no results. In the end, I finally solved it by setting the default value from the OnInit method. I know it means a little bit of more code but it is what resolved it for me.

here you can see an example

LH7
  • 1,385
  • 2
  • 12
  • 16
0

In case you are using reactive forms you need to do that via "setValue" way as [(ngModel)] is deprecated with reactive forms. Code example:

HTML:

<ng-container [formGroup]="appForm">
  <mat-radio-group formControlName="agreement" aria-label="Select an option">
    <mat-radio-button *ngFor="let option of agreementOptions" [value]="option.id">
      {{ option.value }}
    </mat-radio-button>
  </mat-radio-group>
</ng-container>

TS:

export class ExampleComponent implements OnInit {
  appForm = this.fb.group({
    agreement: undefined,
  });

  agreementOptions = [
    { id: 0, value: 'No' },
    { id: 1, value: 'Yes' },
  ];

  constructor(private fb: FormBuilder) {}

  get agreementControl(): FormControl {
    return this.appForm.get('agreement') as FormControl;
  }

  ngOnInit() {
    this.setDeafultFormValues();
  }

  setDeafultFormValues(): void {
    this.agreementControl.setValue(1);
  }
}

And a little bit more extended Demo.

Experimenter
  • 2,084
  • 1
  • 19
  • 26