'Why does ion-radio checked value not get set correctly based on data loaded?

Why does the page load with both radio buttons deselected?

colorSchemes is an array with 2 items.

<ion-radio-group (ionChange)="radioGroupChange($event)" #radioGroup>
  <ion-list *ngFor="let scheme of colorSchemes; let i = index">
    <ion-item class="color-scheme-item-inactive" [ngClass]="{'color-scheme-item-active': scheme.default}">
      <ion-radio
        name="color_radios"
        value="{{scheme.code}}"
        checked="{{scheme.checked}}"
      ></ion-radio>
      <ion-label class="checkbox-label">{{scheme.name}}</ion-label>
     </ion-item>
    </ion-list>
  </ion-radio-group>

and this object stored in colorSchemes:

[{
  checked: true,
  code: "Default",
  default: true,
  expanded: false,
  name: "Default Color Scheme",
}, {
  checked: false
  code: "Alternate"
  default: false
  expanded: false
  name: "Alternate Color Scheme"
}]

I would expected the "Default" radio button to be selected, but when the page loads it's not selected.



Solution 1:[1]

You need to give the default selected value in ion-radio-group, and then whenever you click on another radio button you have to set that value like below code.

Component.html file

  <ion-radio-group (ionChange)="radioGroupChange($event)" [(ngModel)]="selectedValue" #radioGroup>
    <ion-list *ngFor="let scheme of colorSchemes; let i = index">
      <ion-item class="color-scheme-item-inactive" [ngClass]="{'color-scheme-item-active': scheme.default}">
        <ion-radio name="color_radios" [value]="scheme.code"></ion-radio>
        <ion-label class="checkbox-label">{{scheme.name}}</ion-label>
      </ion-item>
    </ion-list>
  </ion-radio-group>

Component.ts file

  colorSchemes = [{
    checked: true,
    code: "Default",
    default: true,
    expanded: false,
    name: "Default Color Scheme",
  }, {
    checked: false,
    code: "Alternate",
    default: false,
    expanded: false,
    name: "Alternate Color Scheme"
  }];
  selectedValue = 'Default'

  radioGroupChange(event) {
    console.log(event.target.value);
    this.selectedValue = event.target.value;
  }

this code working like a charm, I have tried it and tested it.

Working Demo: https://stackblitz.com/edit/ionic-angular-v5-twqrf8?file=src/app/app.component.ts

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1