Programatically check ion-radio inside ngFor

This must be a very basic question but having searched for hours everywhere I can’t seem to find the solution. How can you conditionally check a radio box from within ngFor in a radio-group? For example if I wanted the first item in the list to be the one that is checked?

<ion-list radio-group [(ngModel)]="site">
<ion-item *ngFor="let website of websites; let i = index;">
	<ion-radio value="{{website.site}}" [checked]="i==0"></ion-radio>
	<ion-label>
		Item {{i}}
	</ion-label>
</ion-item>
</ion-list>

Lose the {{}} in your checked binding.

Tried that (have updated the code above to reflect it as well), but same result.

It displays the radio buttons and item list fine, but none are checked.

It seems that the model overrides the checked attribute. Try setting site to websites[0].site in your component constructor and losing the checked business.

Not sure I’m following you… how will it know which radio to check as it goes through them?

It will check whatever one has a value that matches whatever the bound model of the radio group is.

Humm ok maybe I have the whole thing set up wrong.
If I change:

<ion-list radio-group [(ngModel)]="site">

to be

<ion-list radio-group [(ngModel)]="websites[0].site">

then how am I able to grab the value selected by the user downstream? i.e. right now I use:

this.site

to contain the user selected value.

I’m talking about assigning to site itself:

constructor() {
  this.site = this.websites[0].site;
}
2 Likes

Ahhhh yes… ok I understand now. DUH! lol…

Thanks bro!

I’m running into a similar issue using [(ngModel)] in a custom component with a dynamic RadioGroup, but getting the error:

Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

If I remove the [(ngModel)] binding, the RadioGroup renders fine but no RadioButtons are checked.

<ion-list radio-group [(ngModel)]="selection">
  <ion-item *ngFor="let option of options">
    <ion-label>{{option}}</ion-label>
    <ion-radio [value]="option"></ion-radio>
  </ion-item>
</ion-list>

Any idea why this is happening?

1 Like