Mar*_*cok 319 angular2-directives angular
我究竟做错了什么?
import {bootstrap, Component} from 'angular2/angular2'
@Component({
selector: 'conf-talks',
template: `<div *ngFor="let talk in talks">
{{talk.title}} by {{talk.speaker}}
<p>{{talk.description}}
</div>`
})
class ConfTalks {
talks = [ {title: 't1', speaker: 'Brian', description: 'talk 1'},
{title: 't2', speaker: 'Julie', description: 'talk 2'}];
}
@Component({
selector: 'my-app',
directives: [ConfTalks],
template: '<conf-talks></conf-talks>'
})
class App {}
bootstrap(App, [])
Run Code Online (Sandbox Code Playgroud)
错误是
EXCEPTION: Template parse errors:
Can't bind to 'ngForIn' since it isn't a known native property
("<div [ERROR ->]*ngFor="let talk in talks">
Run Code Online (Sandbox Code Playgroud)
Mar*_*cok 629
由于这至少是我第三次在这个问题上浪费超过5分钟,我想我会发布Q&A.我希望它可以帮助别人在路上...可能是我!
我键入in
而不是of
在ngFor表达式中.
Befor 2-beta.17,它应该是:
<div *ngFor="#talk of talks">
Run Code Online (Sandbox Code Playgroud)
从beta.17开始,使用let
语法代替#
.有关详细信息,请参阅更新信息.
请注意,ngFor语法"desugars"到以下内容:
<template ngFor #talk [ngForOf]="talks">
<div>...</div>
</template>
Run Code Online (Sandbox Code Playgroud)
如果我们改用in
它,它就变成了
<template ngFor #talk [ngForIn]="talks">
<div>...</div>
</template>
Run Code Online (Sandbox Code Playgroud)
由于ngForIn
不是具有相同名称的输入属性(如ngIf
)的属性指令,因此Angular会尝试查看它是否是template
元素的(已知的本机)属性,而不是,因此是错误.
更新 - 从2-beta.17开始,使用let
语法而不是#
.这会更新到以下内容:
<div *ngFor="let talk of talks">
Run Code Online (Sandbox Code Playgroud)
请注意,ngFor语法"desugars"到以下内容:
<template ngFor let-talk [ngForOf]="talks">
<div>...</div>
</template>
Run Code Online (Sandbox Code Playgroud)
如果我们改用in
它,它就变成了
<template ngFor let-talk [ngForIn]="talks">
<div>...</div>
</template>
Run Code Online (Sandbox Code Playgroud)
mam*_*udi 236
使用let ...而不是让...在 !!
如果你是新来的角(> 2.X),并可能从Angular1.x迁移,很有可能你混淆in
使用of
.正如Andreas在下面评论中提到for ... of
遍历values
的同时对象for ... in
遍历properties
中的对象.这是ES2015中引入的新功能.
简单地替换:
<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">
Run Code Online (Sandbox Code Playgroud)
同
<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">
Run Code Online (Sandbox Code Playgroud)
因此,您必须使用 inside 指令替换in
of
ngFor
以获取值.
kri*_*hna 14
如果您想使用of
而不是切换到in
. 可以使用KeyValuePipe
6.1 中介绍的。您可以轻松地迭代一个对象:
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
Run Code Online (Sandbox Code Playgroud)
Roh*_*esh 11
尝试导入import { CommonModule } from '@angular/common';
角度最终为*ngFor,*ngIf所有都出现在CommonModule中
使用of而不是in。您可以使用KeyValue Pipe。您可以轻松地迭代一个对象:
<div *ngFor="let items of allObject | keyvalue">
{{items.key}}:{{items.value}}
</div>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
98843 次 |
最近记录: |