How to set default selected value of ion-option?

前端 未结 9 1116
悲&欢浪女
悲&欢浪女 2020-12-09 03:18

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


    

        
相关标签:
9条回答
  • 2020-12-09 03:37
    <ion-select ([ngModel])="dropdown1">
      <ion-select-option value="1">Item1</ion-select-option>
      <ion-select-option value="2">Item2</ion-select-option>
    </ion-select>
    

    the following will not work:

    dropdown1 = 2;
    

    but the following will work:

    dropdown1 = 2 + "";
    

    The select option values are treated as string, so you should assign string values to your model variable so that comparison will not fail.

    0 讨论(0)
  • 2020-12-09 03:40

    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";
    }
    
    0 讨论(0)
  • 2020-12-09 03:47

    The problem seems to be that ion-option don't like objects in rc3. I have to work with only the id part of the object and write a seperate changehandler that find the needed object and set it as a value.

      <ion-select [ngModel]="company.form.id" (ngModelChange)="companyFormSelected($event)" okText="Ok" cancelText="Mégsem">
        <ion-option *ngFor="let form of forms" [value]="form.id" [selected]="form.id == company.form.id">{{form.name}}</ion-option>
      </ion-select>
    

    And the changehandler:

    companyFormSelected(newform) {
        let selectedForm = this.forms.find((f)=>{
          return f.id === newform;
        });
        this.company.form=selectedForm;
    }
    

    This seems to be a bug in rc3 but I don't know where can I report bugs. I did open a topic on ionic forum.

    0 讨论(0)
提交回复
热议问题