在日历的对象数组上使用ngFor

时间:2019-03-01 22:36:46

标签: angular

我将如何使用ngFor遍历以下对象数组并仅获取月份的名称?

{
  "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
  }
}

这是我到目前为止所做的:

<option *ngFor="let date of dates" 
 [ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>

结果:

  

找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到数组等Iterable。

2 个答案:

答案 0 :(得分:5)

使用| keyvalue管道!

angular 6.0.0之前的| keyvalue管道已添加到*ngFor中的渲染对象。

<option *ngFor="let date of dates | keyvalue" 
 [ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>

答案 1 :(得分:4)

*ngFor不能用于遍历对象属性。您需要先将对象转换为可迭代的数据类型。

let dateArray = Object.values(dates) // --> [{"name": "January", "short": "Jan", ...} ...]

在标记中:

<option *ngFor="let date of dateArray" 
  [ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>

或者如果您使用的是6+版本,则只需使用keyvalue管道:

<option *ngFor="let date of dates | keyvalue" 
 [ngValue]="date.name" [(ngModel)]="dobMonth">{{ date.name }}</option>