2

I'm using options tag in Angular 2 to populate my dropdown list. The dropdown list is populating correctly with dateTest1.json, however, when iterating thru the values of a given key in a .json file, then it's having trouble populating the drop down list. What's the correct way in Angular 2 for populating dropdown list with dateTest.json example below?

*.component.html when retrieving from dateTest.json: EXCEPTION: TypeError: Cannot read property 'month' of undefined in [dateAttributesList.month in *Component@63:22]

<option *ngFor="#m of dateAttributesList.month" [value]="m">{{m}}</option>

dateTest.json:

[
    {"month": ["Dec", "Jan", ...]},
    {"day" : ["1","2"...]}
]

*.component.html when retrieving from dateTest1.json: correctly populating

<option *ngFor="#m of dateAttributesList" [value]="m">{{m}}</option>

dateTest1.json:

[
    {"month": "Dec"},
    {"month": "Jan"},
    {"month": "Feb"},
    ...
 ]
jerryh91
  • 1,777
  • 10
  • 46
  • 77

1 Answers1

1

Use the safe navigation operator if the value you bind to is passed by an input or fetched by an async call:

<option *ngFor="#m of dateAttributesList?.month" [value]="m.month">{{m}}</option>

[value] only supports string values. If you have object values use [ngValue]

<option *ngFor="#m of dateAttributesList" [ngValue]="m.month">{{m}}</option>

[ngValue] only works with [ngModel]

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567