ionic 2 Populate从json中选择选项 [英] ionic 2 Populate Select Options from json

查看:141
本文介绍了ionic 2 Populate从json中选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用json对象动态填充 ion-select 下拉列表。

I'm trying to dynamically populate a ion-select dropdown with a json object.

我的html组件如下所示:

My html component looks like this:

<ion-item [hidden]="editOptions.isEditing">
  <ion-note stacked color="primary">{{label}}</ion-note>
  <ion-note class="inline-edit"> {{value}}&nbsp;</ion-note>
</ion-item>
<ion-item [hidden]="!editOptions.isEditing">
  <ion-label stacked color="primary">{{label}}</ion-label>

  <ion-select [(ngModel)]="value" [selectOptions]="additionalData" [required]="required" [name]="value">
    <!--<ion-option>None</ion-option>-->
  </ion-select>
</ion-item>

在我的调用代码中,我尝试填充选择选项,但是他们在那里没有文档

and In my calling code i try to populate the select options but they have no example in there documentation

additionalData = {
  title: 'Pizza Toppings',
  subTitle: 'Select your toppings',
  mode: 'md'
};

如何在不使用html中的* ngFor的情况下将我的选项添加到此选择中?
我更愿意像这样传递它们:

How do I add my options to this select, without using an *ngFor in the html? I would prefer to just pass them like so:

additionalData = {
  title: 'Pizza Toppings',
  subTitle: 'Select your toppings',
  mode: 'md'
  options: [{id:1, description:'Pepperoni'}]
};


推荐答案

[selectOptions] 用于传递创建选项( docs )。所以你应该从你的json-object中创建一个可迭代的并使用 * ngFor

The [selectOptions] are used to pass creation options (docs). So you should make an iterable out of your json-object and use *ngFor.

* ngFor 示例:

*ngFor example:

访问对象键和值的一种巧妙方法是使用 Object.keys ,如答案所示,如下所示。

A neat way of accessing object keys and values are by making use of Object.keys as suggested in this answer and shown below.

@Component({
  selector: 'my-page',
  templateURL: 'my-page.html
})

export class MyPage {
    // Make Object.keys available
    objectKeys = Object.keys;
    value = { option1: 'foo', option2: 'bar' };  

    constructor(){}
}

HTML

...  
    <ion-select [(ngModel)]="value" [required]="true" [name]="value">
        <ion-option *ngFor="let option of objectKeys(value)">
            {{ value[option] }}
        </ion-option>
    </ion-select>
...

这样就没有必要实现一个基本上做的自定义管道了同样的事情。

This way theres no need to implement a custom pipe that basically does the same thing.

这篇关于ionic 2 Populate从json中选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆