我有一个 Angular 5 下拉列表,可以很好地处理硬编码数据,但我需要将其切换为实时数据。问题是实时数据是普通数组。
这是目前有效的
HTML
<select...
<option *ngFor="let activityType of activityTypes" [ngValue]="activityType.Id">
{{activityType.Activity}}
</option>
typescript 组件
activityTypes: any[];
this.activityTypes = [
{ Id: 1, Activity: "Select One" },
{ Id: 2, Activity: "Insert" },
{ Id: 2, Activity: "Update" },
{ Id: 3, Activity: "Delete" },
];
但是,这是我的问题,我从服务中提取数据,数据看起来像这个数组
this.activityTypes v["INSERT", "UPDATE"]
0: "INSERT"
1: "UPDATE"
click to see dev tool image output
现在,如何使用数组绑定(bind)到下拉列表? 显然,我希望将值设置为数组的“0”、“1”.. 然后是显示(这是我在硬编码示例中的事件)我希望它保持“插入”和“更新”.. .
最佳答案
你可以使用数组索引作为选项的值,数据作为标签
<select...
<option *ngFor="let activityType of activityTypes; let i = index" [ngValue]="i">
{{activityType}}
</option>
解决方案 2:您可以创建对象数组:
this.activityTypes = this.activityTypes.map((currElement, index) => {
let obj = {
Id: index,
Activity: currElement
};
return obj;
});
关于javascript - Angular 下拉菜单从硬编码数据切换到来自服务的实时数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50641432/