How to set default selected value of ion-option?

前端 未结 9 1115
悲&欢浪女
悲&欢浪女 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:20

    ion Select tag Just Assign the array to ngModel and default value is selected. Simple

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

    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>
    
    0 讨论(0)
  • 2020-12-09 03:28

    Inside ion-option, you can do

    <ion-option [attr.selected]="(form.name == name) ? true : null"> {{ form.name }} </ion-option>
    
    0 讨论(0)
  • 2020-12-09 03:28
      in html---->
    
         <ion-item text-center >
            <ion-select  [(ngModel)]="selectedQuestion" placeholder="Choose Security Question" >
              <ion-option *ngFor="let q of questionArray let i=index"  selected="{{(i==defaultSelectQuestion).toString()}}"  >
                 {{q}}
                </ion-option>
            </ion-select>
          </ion-item>
    
    
    in ts---->
    //if u dont want any default selection
        this.defaultSelectQuestion = -1; 
    
    //if first element should be your default selection
      this.defaultSelectQuestion = 0;
    
    
    
    this.selectedQuestion=this.questionArray[this.defaultSelectQuestion]
    
    0 讨论(0)
  • 2020-12-09 03:34

    If you deal with default value xor objects, the cleanest way is to provide a compare function to the [compareWith] attribute. This function takes 2 objects in parameters and returns true if they are equals. This way, existing values in model will be selected at start. This works too if new data are added in model outside of the select.

    Following example is taken from official Ionic doc

    <ion-item>
      <ion-label>Employee</ion-label>
      <ion-select [(ngModel)]="employee" [compareWith]="compareFn">
        <ion-option *ngFor="let employee of employees" [value]="employee"></ion-option>
      </ion-select>
    </ion-item>
    
    compareFn(e1: Employee, e2: Employee): boolean {
      return e1 && e2 ? e1.id == e2.id : e1 == e2;
    }
    

    EDIT : using double equals make it work for Ionic 4 (as Stan Kurdziel suggests in comment)

    0 讨论(0)
  • 2020-12-09 03:35
    <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
    
    0 讨论(0)
提交回复
热议问题