2017-07-31 61 views
0

我有離子選擇與有很多選項,我有當視圖準備選擇一個默認值取決於CurrentNumber。我有這樣的代碼:離子選擇選擇默認值不工作

<ion-select formControlName="Level"> 
      <ion-option [value]="level.id" *ngFor="let level of levels" [attr.selected]="(level.levelNumber == currentLevel)? true : null"> 
      {{level.name}} 
      </ion-option> 
</ion-select> 

this.currentLevel = 1; 

數據來自像服務器:

data = [ 
{ 
    levelNumber : 1, 
    name:'abcd' 
}, 
{ 
levelNumber:2, 
name:'efg' 
} 
] 

回答

2

取而代之的是selected屬性,你可以在數據準備好設置控件的默認選項:

// When the data is ready 
this.yourForm.get('Level').setValue(data.id); 

這將設置id爲data.id作爲默認值的選項。

0

然後是這樣的:示例直接從here

* ### Object Value References 
* 
* When using objects for select values, it is possible for the identities of these objects to 
* change if they are coming from a server or database, while the selected value's identity 
* remains the same. For example, this can occur when an existing record with the desired object value 
* is loaded into the select, but the newly retrieved select options now have different identities. This will 
* result in the select appearing to have no value at all, even though the original selection in still intact. 
* 
* Using the `compareWith` `Input` is the solution to this problem 
* 
<ion-item> 
    <ion-label>Employee</ion-label> 
    <ion-select [(ngModel)]="employee" [compareWith]="compareFn"> 
    <ion-option *ngFor="let employee of employees" [value]="employee">{{employee.name}}</ion-option> 
    </ion-select> 
</ion-item> 
compareFn(e1: Employee, e2: Employee): boolean { 
    return e1 && e2 ? e1.id === e2.id : e1 === e2; 
} 
-1

你可以像下面:

<ion-select formControlName="Level"> 
    <ion-option *ngFor="let level of levels" value="{{level.id}}" [selected]="level.levelNumber == currentLevel"> 
    {{level.name}} 
    </ion-option> 
</ion-select> 
1

我找到一種方式與佔位

<ion-select id="genderInput" [formControl]="gender" [placeholder]="gender.value.toUpperCase() | translate"> 
    <ion-option value="female">{{ 'FEMALE' | translate }}</ion-option> 
    <ion-option value="male">{{ 'MALE' | translate }}</ion-option> 
</ion-select> 

還必須添加以下樣式覆蓋的佔位符

ion-select { 
    div.select-text.select-placeholder { 
     color: get-color(black) !important; 
    } 
} 

希望它能幫助:)

+0

感謝尼古拉的默認顏色,我花了年齡試圖解決這個問題。佔位符是要走的路。完美工作 –