Create a drop-down list with custom options text and value in Angular
It is a common practice that the text of the options of a select drop-down box is a combination of a shortcut and it’s full text label.
For example consider the following array of JSON objects that a server might return:
- On the UI-side we want the options on the drop-down box to have the following format: label (shortcut).
- We also want that the value property of each option contains the country shortcut, so that it’s easier for the server to parse the selected options later.
- Moreover, since the server might return hundreds of options, we want a way to dynamically generate the option elements.
Angular has a solution to all three previous requests. Consider the following code:
The track by defines which property is going to be used as value on the option element and the combineCountryShortcutWithLabel(country) is the function inside the Angular controller which combines the strings of the two properties:
More information on the ngOptions directive can be found in the official Angular documentation.