角度异常:无法绑定到'ngForIn',因为它不是已知的本机属性

问题描述 投票:279回答:8

我究竟做错了什么?

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">
angular angular2-directives
8个回答
580
投票

由于这至少是我第三次在这个问题上浪费超过5分钟,我想我会发布Q&A。我希望它可以帮助别人在路上...可能是我!

我在ngFor表达式中输入了in而不是of

在2-beta.17之前,它应该是:

<div *ngFor="#talk of talks">

从beta.17开始,使用let语法而不是#。有关详细信息,请参阅更新信息。


请注意,ngFor语法“desugars”到以下内容:

<template ngFor #talk [ngForOf]="talks">
  <div>...</div>
</template>

如果我们改用in,它会变成

<template ngFor #talk [ngForIn]="talks">
  <div>...</div>
</template>

由于ngForIn不是具有相同名称的输入属性的属性指令(如ngIf),因此Angular会尝试查看它是否是template元素的(已知的本机)属性,并且它不是,因此是错误。

更新 - 从2-beta.17开始,使用let语法而不是#。这会更新到以下内容:

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

请注意,ngFor语法“desugars”到以下内容:

<template ngFor let-talk [ngForOf]="talks">
  <div>...</div>
</template>

如果我们改用in,它会变成

<template ngFor let-talk [ngForIn]="talks">
  <div>...</div>
</template>

208
投票

TL; DR;

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


如果你是Angular(> 2.x)的新手并且可能从Angular1.x迁移,很可能你会把inof混淆。正如andreas在下面的评论中提到的,for ... of迭代一个对象的valuesfor ... in在一个对象中迭代properties。这是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指令中的of替换ngFor来获取值。


20
投票

而不是:

  template: `<div *ngFor="let talk in talks">

用于:

  template: `<div *ngFor="let talk of talks">

希望这能解决问题。


11
投票

在我的情况下,WebStrom自动完成插入小型*ngfor,即使它看起来你选择了正确的骆驼套管(*ngFor)。


8
投票

尝试在角度决赛中导入import { CommonModule } from '@angular/common';,因为*ngFor*ngIf都出现在CommonModule


6
投票

我的问题是,Visual Studio在复制和粘贴时以某种方式自动将*ngFor降级为*ngfor


-3
投票

问:无法绑定到'pSelectableRow',因为它不是'tr'的已知属性。

答:您需要在ngmodule中配置primeng tabulemodule


-13
投票

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

<div ngFor="let talk in talks">
© www.soinside.com 2019 - 2024. All rights reserved.