angular2中的[ngFor]和[ngForOf]有什么区别? [英] What is the difference between [ngFor] and [ngForOf] in angular2?
问题描述
据我了解,两者都在执行相同的功能.但是,
我的理解正确吗?或者
ngFor
和ngForOf
并不是两个截然不同的东西,它们实际上是NgForOf指令的选择器.
如果您查看源,您会看到NgForOf指令的选择器为[ngFor][ngForOf]
,这意味着两个元素都必须存在于元素上才能使指令激活".
使用*ngFor
时,Angular编译器将该语法解糖为规范形式,该规范在元素上同时具有两个属性.
所以
<div *ngFor="let item of items"></div>
对以下对象不满意:
<template [ngFor]="let item of items">
<div></div>
</template>
第一次脱糖是由于'*'.下一个脱糖的原因是微观语法:让物品项". Angular编译器对此进行了除糖处理:
<template ngFor let-item="$implicit" [ngForOf]="items">
<div>...</div>
</template>
(您可以将$ implicit视为该指令用来在迭代中引用当前项的内部变量).
ngFor属性以规范形式表示,而ngForOf属性实际上是指令的输入,该指令指向要迭代的事物列表.
您可以查看角度微语法指南了解更多信息.
As per my understanding, Both are doing the same functions. But,
ngFor
would be works like as collections?.ngForOf
would be works like as generics?.
Is my understanding is correct? or Could you please share more difference's(details) about
ngFor
andngForOf
?
ngFor
and ngForOf
are not two distinct things - they are actually the selectors of the NgForOf directive.
If you examine the source, you'll see that the NgForOf directive has as its selector: [ngFor][ngForOf]
, meaning that both attributes need to be present on an element for the directive to 'activate' so to speak.
When you use *ngFor
, the Angular compiler de-sugars that syntax into its cannonical form which has both attributes on the element.
So,
<div *ngFor="let item of items"></div>
desugars to:
<template [ngFor]="let item of items">
<div></div>
</template>
This first de-sugaring is due to the '*'. The next de-sugaring is because of the micro syntax: "let item of items". The Angular compiler de-sugars that to:
<template ngFor let-item="$implicit" [ngForOf]="items">
<div>...</div>
</template>
(where you can think of $implicit as an internal variable that the directive uses to refer to the current item in the iteration).
In its canonical form, the ngFor attribute is just a marker, while the ngForOf attribute is actually an input to the directive that points to the the list of things you want to iterate over.
You can check out the Angular microsyntax guide to learn more.
这篇关于angular2中的[ngFor]和[ngForOf]有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!