Ionic3应用中如何用对象在ion-select生成动态ion-option
在Ionic3中动态生成国家选择项的实现方法
这个需求在Ionic3里其实很好实现,核心是借助Angular的*ngFor指令动态生成选项,不过因为你手里的是键值对形式的对象,直接用*ngFor循环不了,得先把它转换成数组结构,我给你一步步拆解:
1. 组件代码(.ts文件)
首先在你的页面组件里,把国家对象转换成包含code和name的数组,同时定义好绑定ngModel的变量:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'page-country-select', templateUrl: 'country-select.html', }) export class CountrySelectPage implements OnInit { // 你的原始国家对象 private countryObject = {AF: "Afghanistan", AX: "Aland Islands", AL: "Albania", DZ: "Algeria"}; // 转换后的数组,用来循环生成选项 public countries: Array<{code: string, name: string}> = []; // 绑定ngModel的变量,存储选中的国家代码 public country: string; ngOnInit() { // 将键值对对象转换为数组 this.countries = Object.keys(this.countryObject).map(key => ({ code: key, name: this.countryObject[key] })); } }
2. 模板代码(.html文件)
接下来在模板里用*ngFor遍历转换后的数组,动态生成ion-option:
<ion-select [(ngModel)]="country" interface="action-sheet"> <!-- 循环生成每个国家选项 --> <ion-option *ngFor="let item of countries" [value]="item.code"> {{item.name}} </ion-option> </ion-select>
这样运行起来,就会自动生成你想要的所有国家选项啦。如果你的国家数据是从后端API获取的,只需要把转换数组的逻辑放在数据请求成功的回调里就行。
内容的提问来源于stack exchange,提问作者GAURAV
相关产品推荐
相关产品推荐

