SGN SGN - 1 year ago 87
TypeScript Question

How do I add options to a drodown in angular 2

I have a dropdown which contains the months of the years which are translated with a pipe like this

{{'January' | translate}}

I want to bind my months in my dropdown, here is my is my html and my months object:

<select class="small">
<option selected="selected">--{{ 'Year' | translate | capitalize }}--</option>
<option *ngFor=".."></option>

1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'

Answer Source

Currently angular 2 does not allow you to iterate over an object using *ngFor. You have a couple of options to work around this limitation.

1.) map the object to an array of values, and use *ngFor to iterate over that. This solution does not give you access to the keys, however. If you need access to the keys as well, you can use option 2.

2.) get an array of the objects keys, ex. let keys = Object.keys(MONTH_TRANSLATION) you can then *ngFor over the array of keys, and then use each key to look up the corresponding value. using Object.keys() does not guarantee the sort order of your keys, so to be safe you can sort the array of keys after you obtain it

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download