简体   繁体   English

如何动态地在离子2中的下拉列表中添加值

[英]How to add values in dropdown in ionic 2 dynamically

I want a dropdown in my form. 我想在我的表格中下拉。 I know how to add options in dropdown statically, but, I want it to be dynamic. 我知道如何静态地在下拉列表中添加选项,但是,我希望它是动态的。

My code 我的代码

<ion-item>
    <ion-label>Select Type</ion-label>
    <ion-select [(ngModel)]="selectedvalue" #item>
        <ion-option *ngFor="let item of items" [value]="item">{{item}}</ion-option>
    </ion-select>
</ion-item>

I have written the html code for this. 我为此编写了html代码。 But I don't know what to do in my .ts file. 但我不知道在我的.ts文件中该怎么做。 How to assign values to items? 如何为项目赋值?

What you need to do in your code is define the options array and a variable for the selected option in Page.ts and at some point populate it with option objects. 您需要在代码中执行的操作是定义选项数组和Page.ts中所选选项的变量,并在某些时候使用选项对象填充它。 So define the array like this... (i'm using TypeScript definitions for each property here because why not) 所以像这样定义数组......(我在这里为每个属性使用TypeScript定义,因为为什么不呢)

export class Page {
    selectedValue: number;
    optionsList: Array<{ value: number, text: string, checked: boolean }> = [];

    constructor() { }

Alternatively just something like this should also work... 或者像这样的东西也应该工作......

    optionsList: any[] = [];

And then populate the array with option objects (each object should have 2 properties and optionally a 3rd if you want to pre-select an option). 然后使用选项对象填充数组(如果要预先选择一个选项,每个对象应该有2个属性,并且可选择第三个属性)。

Where you do this will depend on if it is being populated asynchronously or not. 您执行此操作将取决于它是否异步填充。 For this example I will just do it in the constructor... 对于这个例子,我将在构造函数中执行它...

constructor() {
     this.optionsList.push({ value: 1, text: 'option 1', checked: false });
     this.optionsList.push({ value: 2, text: 'option 2', checked: false });
}

And your HTML code should look something like this... 你的HTML代码应该看起来像这样......

<ion-select [(ngModel)]="selectedvalue">
    <ion-option *ngFor="let item of optionsList" value="{{item.value}}" checked="{{item.checked}}">{{item.text}}</ion-option>
</ion-select>

You need to have one model and one array. 您需要一个模型和一个数组。 Array will contain set of items which will be displayed in "select". 数组将包含将在“选择”中显示的一组项目。

The component code will look like below: 组件代码如下所示:

export class Modal {

categories = [
 {
   title: 'Locked',
   price: 100 
 },
 {
   title: 'Liquid',
   price: 8000
 }];         

 selectedCategory = this.categories[0]; 

}

Template code will look like below: 模板代码如下所示:

<ion-item>
    <ion-select [(ngModel)]="selectedCategory">
          <ion-option *ngFor="let category of categories;" 
                  [value]="category">{{category.title}}</ion-option>      
    </ion-select>
</ion-item> 

Hope this will help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM