Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70429

Problem binding ngModel to RadioGroup with an array of obects

$
0
0

@AlGantori wrote:

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];
  }

and

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

<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 ngModel?:

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

That does not feel right.

Thank you.

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70429

Trending Articles