How to set default selected value of ion-option?

2019-01-18 12:42发布

I'm using Ionic v2 and I can not set the selected value when showing the page.

<ion-select [(ngModel)]="company.form">
    <ion-option *ngFor="let form of forms" [value]="form" [selected]="true">{{form.name}}</ion-option>
</ion-select>

I've tried with checked, too but that isn't work either. How can I do this?

Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.13
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.45

9条回答
The star\"
2楼-- · 2019-01-18 13:23
<ion-select [(ngModel)]="name">// binding the value available from ts file
    <ion-option *ngFor="let form of forms; let idx = index" [value]="form.name"  selected="{{(idx==0).toString()}}">{{form.name}}</ion-option>
</ion-select>

inside your ts file

name = this.forms[0].name //assign the variable name to the first index of your array
查看更多
女痞
3楼-- · 2019-01-18 13:23

This is working for me.

In html :

<ion-select [(ngModel)]="company.form">
    <ion-option value="frm1"> Form 1 </ion-option>
    <ion-option value="frm2"> Form 2 </ion-option>
</ion-select>

In ts :

company = {
   form:null
}; 

constructor(){
   this.company.form = "frm1";
}
查看更多
疯言疯语
4楼-- · 2019-01-18 13:25

You do not need to work with the attribute selected or [selected] it is not necessary

<ion-select [(ngModel)]="company.form.id" name="company.form.id">
    <ion-option *ngFor="let form of forms" value="{{ form.id }}">
      {{ form.name }}
    </ion-option>
</ion-select>
查看更多
登录 后发表回答