2016-12-14 74 views
3

我正在使用Ionic v2,並且在顯示頁面時無法設置所選值。我也試過checked,但這也不行。我怎樣才能做到這一點?如何設置離子選項的默認選定值?

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

試試這個:'this.company.form = this.forms'在[0]您'component.ts' –

回答

1

你並不需要選擇或屬性的工作[選擇]沒有必要

<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

據我所知,這是一個離子v2 rc-3中的bug,並在最終版本中得到修復。我想你的解決方案現在正在工作,看起來應該工作的方式,我的解決方案是rc-3中的錯誤的解決方法。因此,爲了將來的參考,我將您的答案設置爲我原始問題的最佳解決方案。感謝您的回答! – Perrier

4
<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 
+0

這個工作嗎?看來你現在已經將select上的'ngModel'綁定到了一個字符串,但是選項值是所有的對象。 – Lex

+0

無法使用名稱屬性。 – Perrier

+0

好的,至少它表明rc3中的這個離子選項實際上可以顯示默認值。然而,解決方案不是使用它中的對象,也不需要使用索引。感謝您的時間@MohanGopi – Perrier

0

內離子選項,你可以做

<ion-option [attr.selected]="(form.name == name) ? true : null"> {{ form.name }} </ion-option> 
+0

沒有工作。試着用[attr.checked],但也沒有做到這一點。你使用相同的離子版本,這對你有用嗎? – Perrier

9

這個問題似乎是離子選擇不喜歡的對象在rc3中。我只需要處理對象的id部分,然後編寫一個單獨的changehandler來查找所需的對象並將其設置爲值。

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

而且changehandler:

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

這似乎是在RC3一個錯誤,但我不知道我在哪裏報告問題。我確實打開了一個topic on ionic forum

0
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]