离子2:如何将<ion-select>绑定到选项键?

时间:2017-09-13 16:19:28

标签: angular typescript ionic-framework ionic2

我正在开发我的第一个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设置为所选状态的密钥。因此,例如,如果用户选择&#34;阿肯色州&#34;从下拉列表中,customer.state的值将成为字符串&#34; ar&#34;。 如何实现这一目标?

<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>个,所以如果可以的话,我会更喜欢干净简洁的东西。

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以在

中使用Object.keys()
<ion-select [(ngModel)]="customer.state">
    <ion-option *ngFor="let key of stateOptionKeys"></ion-option>
</ion-select>

并在组件的stateOptionKeys方法中定义ngOnInit()

this.stateOptionKeys = Object.keys(this.stateOption);

您还必须将stateOptionKeys声明为组件类的array - 属性。

答案 1 :(得分:0)

这对我有用:

<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>