简体   繁体   中英

Angular - Mapping form value with array value

I have an array:

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

I have a HTML Select

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

However, my form is updated with values from a database. In the database, the value for the choice is choice_confirmed_unconfirmed or choice_in_out .

Is it possible that when i patch my angular form that the HTML select will display a value from the array that matches the returned value from the database?

For example, if the form value returns as choice_in_out , then the select dropdown will be preselected with In / Out ?

Is there a way to bind the database format for those values with how I want them to display in the drop down?

You can have a mapping object instead of an array and have strings mapped with what you want to display, while keeping the value same as you get from 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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