Angular 2: *ngFor 变体

Angular 2: *ngFor variant

*ngFor='let n in list'*ngFor='let n of list' 之间有什么区别 我最近偶然发现了它。翻了几个老问题没找到满意的答案。

in JavaScript

for…in 语句迭代对象的可枚举属性

for…of 语句循环遍历一个可迭代对象,一个一个地获取它的每个值

语法

*ngFor='let n in list'

是无效的 Angular 语法。

为了证明这一点,使用最小 app.component.ts 文件创建一个新的 angular 项目:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <ul>
    <li *ngFor="let n in list">{{n}}</li>
  </ul>
  `
})
export class AppComponent {
  public list = [1,2,3,4,5];
}

结果出错

compiler.js:486 Uncaught Error: Template parse errors:
Can't bind to 'ngForIn' since it isn't a known property of 'li'. ("
  <ul>
    <li [ERROR ->]*ngFor="let n in list">{{n}}</li>
  </ul>
  "): ng:///AppModule/AppComponent.html@2:8
Property binding ngForIn not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("
  <ul>
    [ERROR ->]<li *ngFor="let n in list">{{n}}</li>
  </ul>

但是您可以创建自定义指令来处理此问题(如 this article 中所述)。

关于和的区别,文中提到如下:

NgFor is Angular’s equivalent of the for…of statement in JavaScript, looping over an iterable object and taking each of its values one by one. There’s also the for…in statement which instead iterates over the enumerable properties of an object, but there’s no Angular equivalent to that, so let’s make one.