首页 > 解决方案 > Angular - 将表单值与数组值映射

问题描述

我有一个数组:

myArray = [ "Confirmed / Unconfirmed", "In / Out" ]

我有一个 HTML 选择

<select formControlName="choice_type">
   <option></option>
   <option *ngFor="let choice of myArray" [value]="choice"> {{ choice }} </option>
</select>

但是,我的表单使用数据库中的值进行了更新。在数据库中,选择的值为choice_confirmed_unconfirmedchoice_in_out

是否有可能当我修补我的角度表单时,HTML 选择将显示数组中与数据库返回值匹配的值?

例如,如果表单值返回为choice_in_out,则选择下拉菜单将被预选为In / Out?

有没有办法将这些值的数据库格式与我希望它们在下拉列表中的显示方式绑定?

标签: htmlarraysangularselect

解决方案


您可以使用映射对象而不是数组,并将字符串映射到要显示的内容,同时保持与从 DB 获得的值相同。

myArray = {
     choice_confirmed_unconfirmed: "Confirmed / Unconfirmed"
     choice_in_out: "In / Out"
}

<option *ngFor="let choice of myArray | keyvalue" [value]="choice.key"> 
   {{ choice.value }}
</option>

推荐阅读