我做错了什么?

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, [])

错误是

EXCEPTION: Template parse errors:
Can't bind to 'ngForIn' since it isn't a known native property
("<div [ERROR ->]*ngFor="let talk in talks">

当前回答

TL; diana;

使用让…而不是let…在! !


如果你刚接触Angular (>2.x),而且可能是从Angular1迁移过来的。X,很可能你把它和of搞混了。正如andreas在下面的评论中提到的……Of迭代对象的值,而for…In迭代对象中的属性。这是ES2015中引入的新特性。

简单地替换:

<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">

<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">

因此,你必须将in替换为ngFor指令中的of来获取值。

其他回答

为了增加更多的问题,我天真地发现,如果你不使用let语句来分配循环的索引,你也会得到同样的错误:

<span *ngFor="let button of buttons; i: index; trackBy: trackBy">
...
</span>

也抛出相同的错误。下面的版本修复了它

<span *ngFor="let button of buttons; let i = index; trackBy: trackBy">
...
</span>

我的解决方案是-只需从表达式^__^中删除'*'字符

<div ngFor="let talk in talks">

在我的情况下,WebStrom自动完成插入小写*ngfor,即使看起来你选择了正确的驼峰大小写(* ngfor)。

简单地把“in”改成“of”就解决了同样的问题。

Chnage <div *ngFor="let talk in talks">

to     <div *ngFor="let talk of talks">

我的问题是,Visual Studio在复制粘贴时自动将*ngFor小写为*ngFor。