Problem binding ngModel to RadioGroup with an array of obects

I have the following

  fruits: any;
  selection: any;
  ngOnInit(): void {

    this.fruits = [ 
      {name:"apple", color:"red"},
      {name:"banana", color:"yellow"},
      {name:"cherimoya", color:"green"}
  setObject() {
    // I am trying to restore this.selection from Storage something like this:...
    this.selection = {name:"banana", color:"yellow"};  // this won't work
  clear() {
    this.selection = null ;
  setObjectFromArray() {
    this.selection = this.fruits[2]; 


<ion-content padding>
<ion-list radio-group [(ngModel)]="selection">
  <ion-item *ngFor="let fruit of fruits">
    <ion-radio [value]="fruit"></ion-radio>

<button ion-button (click)="setObject()">set to an object banana</button>
<button ion-button (click)="setObjectFromArray()">set to an object from array</button>
<button ion-button (click)="clear()">Clear</button>

Here is the plunker

I kind of understand the RadioGroup is trying to match against the same element instance of the array of objects for it to work.

I am saving the user selection object to Storage and restoring it as an ojbect but, of course the RadioGroup won’t restore it.

How do I rewrite and fix this?

Do I have to make my fruitListService return an additional simple array containing just the names like so and use that for the *ngFor?:

fruits = [ "apple", "banana", "cherimoya", ....]

That does not feel right.

Thank you.

Here is my fix…

<p>this radio group specification works...</p>
<ion-list radio-group [(ngModel)]="">
  <ion-item *ngFor="let fruit of fruits">
    <ion-radio [value]=""></ion-radio>

Here is the fixed plunker…

1 Like