*ngFor='let n in list'
和 *ngFor='let n of list'
之间有什么区别
我最近才偶然发现它。搜索了一些老问题没有找到满意的答案。
最佳答案
语法
*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 中所述)。
至于of和的区别,文章中提到了以下几点:
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.
关于angular2-directives - 角度 2 : *ngFor variant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51462448/