angular2-directives - 角度 2 : *ngFor variant

标签 angular2-directives

*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和的区别,文章中提到了以下几点:

NgFor is Angular’s equivalent of the for…of statement in JavaScript, looping over an iterable object and taking each of its values one by one. There’s also the for…in statement which instead iterates over the enumerable properties of an object, but there’s no Angular equivalent to that, so let’s make one.

关于angular2-directives - 角度 2 : *ngFor variant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51462448/

相关文章:

angular - 指令单击外 Angular 6

javascript - 指令中的范围 true 给出了错误的结果

javascript - Angular 2关注点击/事件后的第一个无效输入

Angular 结构指令 : wrap the host element with some another component

javascript - Angular 2 : what expressions can we interpolate in template

angular2-directives - 如何在 Angular 2 指令中使用 templateUrl

html - 当绑定(bind)到 ngFor 中的值时,Angular 指令会失去其样式

angular - 如何在不循环所有内容的情况下获取 Angular2 模板中数组的最后一个元素?

javascript - Angular 2将html属性从父级传递给子级

Angular 2指令错误