【发布时间】:2018-07-22 05:59:39
【问题描述】:
*ngFor='let n in list' 和 *ngFor='let n of list' 有什么区别
我最近才偶然发现它。翻了一些老问题也没找到满意的答案。
【问题讨论】:
-
阅读此文档可能对您有所帮助medium.com/@jsayol/…
*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和of的区别,文中提到如下:
NgFor 相当于 Angular 中的 for...of 语句,循环遍历一个可迭代对象并一个一个地获取它的每个值。还有 for...in 语句,它会迭代对象的可枚举属性,但没有 Angular 与之等效,所以让我们做一个。
【讨论】:
在 JavaScript 中
for...in 语句,而是迭代对象的可枚举属性
和
for...of 语句循环遍历一个可迭代对象,一个接一个地获取其每个值
【讨论】: