How to set default value for ion option?

I am using Ionic v2 and I cannot set the selected value when the page is displayed.

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

I also tried with checked, but this also does not work. 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
+4
source share
5 answers

You do not need to work with the selected attribute or [selected], which is optional

<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>
+2
source

The problem is that the ion option does not like objects in rc3. I need to work only with the identification part of the object and write a separate change mechanism that finds the desired object and sets 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 changer:

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

, rc3, , . .

+11
<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>

ts

name = this.forms[0].name //assign the variable name to the first index of your array
+4

<ion-option [attr.selected]="(form.name == name) ? true : null"> {{ form.name }} </ion-option>
+1
  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]
+1

Source: https://habr.com/ru/post/1663761/


All Articles