Reputation: 13206
How would I use ngFor to loop through the following object array and get only the names of the months?
{
"Jan": {
"name": "January",
"short": "Jan",
"number": 1,
"days": 31
},
"Feb": {
"name": "February",
"short": "Feb",
"number": 2,
"days": 28
},
"Mar": {
"name": "March",
"short": "Mar",
"number": 3,
"days": 31
},
"Apr": {
"name": "April",
"short": "Apr",
"number": 4,
"days": 30
},
"May": {
"name": "May",
"short": "May",
"number": 5,
"days": 31
},
"Jun": {
"name": "June",
"short": "Jun",
"number": 6,
"days": 30
},
"Jul": {
"name": "July",
"short": "Jul",
"number": 7,
"days": 31
},
"Aug": {
"name": "August",
"short": "Aug",
"number": 8,
"days": 31
},
"Sep": {
"name": "September",
"short": "Sep",
"number": 9,
"days": 30
},
"Oct": {
"name": "October",
"short": "Oct",
"number": 10,
"days": 31
},
"Nov": {
"name": "November",
"short": "Nov",
"number": 11,
"days": 30
},
"Dec": {
"name": "December",
"short": "Dec",
"number": 12,
"days": 31
}
}
This is what I have done so far:
<option *ngFor="let date of dates"
[ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>
Result:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Upvotes: 2
Views: 781
Reputation: 21688
Use | keyvalue
pipe!
angular 6.0.0
onwards | keyvalue
pipe added to render object in *ngFor
.
<option *ngFor="let date of dates | keyvalue"
[ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>
Upvotes: 6
Reputation: 7427
*ngFor
cannot be used to loop over object properties. You'll need to convert the object to an iterable data type first.
let dateArray = Object.values(dates) // --> [{"name": "January", "short": "Jan", ...} ...]
in the markup:
<option *ngFor="let date of dateArray"
[ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>
or if you're using version 6+, just use the keyvalue
pipe:
<option *ngFor="let date of dates | keyvalue"
[ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>
Upvotes: 5