问题
I have ion-select with that have many options and I have when the view is ready to select one default value depending on CurrentNumber. i have this code:
<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;
the data comes from the server like that :
data = [
{
levelNumber : 1,
name:'abcd'
},
{
levelNumber:2,
name:'efg'
}
]
回答1:
Instead of the selected attribute, you can set the default option in the control when the data is ready:
// When the data is ready
this.yourForm.get('Level').setValue(data.id);
That will set the option with id equal to data.id as the default.
回答2:
I find a way with the placeholder
<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>
also have to add the following styles to override the default color of a placeholder
ion-select {
div.select-text.select-placeholder {
color: get-color(black) !important;
}
}
hope it helps :)
回答3:
Then there is this: Example straight from 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;
}
回答4:
You can do it like below:
<ion-select formControlName="Level">
<ion-option *ngFor="let level of levels" value="{{level.id}}" [selected]="level.levelNumber == currentLevel">
{{level.name}}
</ion-option>
</ion-select>
来源:https://stackoverflow.com/questions/45419910/ion-select-select-default-value-not-working