我正在开发我的第一个离子2应用程序。我有一个带有动态选项列表的<ion-select>
。该列表在我的组件中表示为简单字典(名为stateOptions
):
import { Component } from '@angular/core';
@Component({
templateUrl: './test.html'
})
export class TestPage {
stateOptions: {
al: 'Alabama',
ak: 'Alaska',
az: 'Arizona',
ar: 'Arkansas'
}
customer: {
street_address: '123 Sunshine Lane',
city: 'Phoenix',
state: 'az'
}
}
在我看来,我想配置<ion-select>
,以便将customer.state
设置为所选状态的密钥。因此,例如,如果用户从下拉列表中选择" Arkansas",则customer.state
的值将成为字符串" AR"。我该如何实现?
<ion-item>
<ion-label>State</ion-label>
<ion-select [(ngModel)]="customer.state">
<ion-option *ngFor="???"></ion-option>
</ion-select>
</ion-item>
<p>Current value of customer.state: {{ customer.state }}</p>
在Angular 1中,这很容易通过Ngoptions指令来完成:
<select ng-model="customer.state" ng-options="abbr as name for ( abbr, name ) in stateOptions"></select>
...但似乎<ion-select>
不支持此。
这是我看到的一种解决方案:在初始化时,将stateOptions
转换为更易于使用的格式。在组件中,我可以做到这一点:
stateOptionsFormatted: Array<Object> = [];
constructor() {
for (var key in this.stateOptions) {
this.stateOptionsFormatted.push({
abbr: key,
name: this.stateOptions[key]
});
}
}
和视图:
<ion-select [(ngModel)]="customer.state">
<ion-option *ngFor="let stateOption of stateOptionsFormatted" [value]="stateOption.abbr">{{ stateOption.name }}</ion-option>
</ion-select>
这有效,但这是额外的样板代码,可以实现Angular 1中的单线。
我还看到了一个解决方案,该解决方案涉及自定义管道在视图中进行此转换的解决方案 - 但其他人则说这对性能不利,因为它会在用户与页面交互时多次运行。
有更好的选择吗?整个应用程序中都会有很多 <ion-select>
s,所以如果可用,我会更喜欢干净和简洁的东西。
谢谢!
您可以使用
中的Object.keys()
<ion-select [(ngModel)]="customer.state">
<ion-option *ngFor="let key of stateOptionKeys"></ion-option>
</ion-select>
并在组件的ngOnInit()
方法中定义stateOptionKeys
为
this.stateOptionKeys = Object.keys(this.stateOption);
您还必须将stateOptionKeys
声明为array
-组件类的范围。
这对我有用:
<ion-select cancelText="cancel" okText="ok" [(ngModel)]="model.cityid" name="cityid">
<ion-select-option [(value)]="city.id" *ngFor="let city of cities">{{city.title}}</ion-select-option>
</ion-select>