0
votes

selected = "m.selected" shows the selectbox empty when the page opens, even though the value is True. (This problem is experienced in ionic 4 & 5.)

details.page.html

<ion-item mode="ios">
     <ion-label>Unit</ion-label>
    <ion-select [(ngModel)]="selectedModel" mode="ios" interface="action-sheet">
       <ion-select-option *ngFor="let m of details?.unit" [value]="m" [selected]="m.selected">{{m.title}}</ion-select-option>
     </ion-select>
  </ion-item>

<div *ngIf="selectedModel">
<div>
{{selectedModel.name}}
</div>
...
 </div>

details.page.ts

selectedModel:any;
  constructor(private route:ActivatedRoute, private unitService: UnitService) { }

  ngOnInit() {
    let index = this.route.snapshot.paramMap.get('index');
    this.unitService.getUnDetails(index).subscribe(details =>{
      console.log('Details:', details);
      this.details = details;
    })
  }

}

data.json

[
    {
        "id":1,
        "name":"Food",
        "img":"food.jpg",
        "gm":"gr",
        "vitc":"0",
        "vita":"0.04",
        "unit":[
            {
                "i":1,
                "selected":"true",
                "title":"Full",
                "name":"Joe",
                "amount":"25"
            },
            {
                "i":2,
                "selected":"false",
                "title":"Half",
                "name":"Brad",
                "amount":"150"
            }
        ]
    },
    ...
   ]

How do I get the first value selected? I'm getting the data from Api.

1
I can't see any error in your code. Any chance we could see a sample of the data which is returned in details.unit? - andypotato
Okay. I edited and added data. - ucnumara

1 Answers

1
votes

EDIT

Try setting the selectedModel to the selected value in ngOnInit. So something like:

this.selectedModel = this.details.unit.find(u => u.selected);

I don't have full info on the this.details.unit variable, so I'm assuming a little bit on that info.