离子选择选择默认值不工作
问题描述:
我有离子选择与有很多选项,我有当视图准备选择一个默认值取决于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'
}
]
答
取而代之的是selected
属性,你可以在数据准备好设置控件的默认选项:
// When the data is ready
this.yourForm.get('Level').setValue(data.id);
这将设置id为data.id
作为默认值的选项。
答
然后是这样的:示例直接从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;
}
答
你可以像下面:
<ion-select formControlName="Level">
<ion-option *ngFor="let level of levels" value="{{level.id}}" [selected]="level.levelNumber == currentLevel">
{{level.name}}
</ion-option>
</ion-select>
答
我找到一种方式与占位
<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;
}
}
希望它能帮助:)
感谢尼古拉的默认颜色,我花了年龄试图解决这个问题。占位符是要走的路。完美工作 –