我有离子选择,有很多选项,当视图准备好根据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'
}
]
答案 0 :(得分:5)
而不是selected
属性,您可以在数据准备就绪时在控件中设置默认选项:
// When the data is ready
this.yourForm.get('Level').setValue(data.id);
这将设置id等于data.id
的选项作为默认选项。
答案 1 :(得分:3)
我找到了占位符的方法
<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;
}
}
希望它有所帮助:)
答案 2 :(得分:1)
然后有:直接来自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;
}
答案 3 :(得分:0)
只需执行以下操作:
HTML-
<ion-select formControlName="Level">
<ion-option [value]="level.id" *ngFor="let level of levels" >
{{level.name}}
</ion-option>
</ion-select>
TS-
__formGroupInstance : FormGroup
this.__formGroupInstance = this.formBuilder.group({
Level: this.currentLevel
})
答案 4 :(得分:0)
当您的选项不是动态和静态时,您可以执行此操作-
在您的打字稿中:-
this.myForm= this.formBuilder.group({
selectOptionName: ['ValueHere', Validators.required]
});
在您的HTML中:-
<ion-select formControlName = 'selectOptionName' value="ValueHere">
<ion-select-option value="ValueHere">Value-1</ion-select-option>
<ion-select-option value="ValueHere2">Value-2</ion-select-option>
</ion-select>
答案 5 :(得分:-2)
你可以这样做:
<ion-select formControlName="Level">
<ion-option *ngFor="let level of levels" value="{{level.id}}" [selected]="level.levelNumber == currentLevel">
{{level.name}}
</ion-option>
</ion-select>