【问题标题】:Ionic 2: How to bind <ion-select> to an option's key?Ionic 2:如何将 <ion-select> 绑定到选项的键?
【发布时间】:2018-02-22 10:52:30
【问题描述】:

我正在开发我的第一个 Ionic 2 应用程序。我有一个带有动态选项列表的&lt;ion-select&gt;。该列表在我的组件中表示为一个简单的字典(名为 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'
    }

}

在我看来,我想配置&lt;ion-select&gt;,以便将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>

...但似乎&lt;ion-select&gt; 不支持这个。

这是我见过的一个解决方案: 在初始化时,将 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 中的单行代码。

我还看到了一个解决方案,它涉及在视图中执行此转换的自定义管道 - 但其他人说这对性能不利,因为它会在用户与页面交互时运行多次。

还有更好的选择吗?在我的应用程序中会有很多&lt;ion-select&gt;s,所以如果有的话,我更喜欢简洁明了的东西。

谢谢!

【问题讨论】:

    标签: angular typescript ionic-framework ionic2


    【解决方案1】:

    你可以使用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-属性。

    【讨论】:

    • 谢谢!这就是我最终做的。它仍然比我更喜欢的样板,但它似乎是最好的选择。
    【解决方案2】:

    这对我有用:

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

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2017-05-05
      • 1970-01-01
      • 2020-03-29
      相关资源
      最近更新 更多