【发布时间】:2018-02-22 10:52:30
【问题描述】:
我正在开发我的第一个 Ionic 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,所以如果有的话,我更喜欢简洁明了的东西。
谢谢!
【问题讨论】:
标签: angular typescript ionic-framework ionic2