【问题标题】:Angular 2: *ngFor variantAngular 2:*ngFor 变体
【发布时间】:2018-07-22 05:59:39
【问题描述】:

*ngFor='let n in list'*ngFor='let n of list' 有什么区别 我最近才偶然发现它。翻了一些老问题也没找到满意的答案。

【问题讨论】:

标签: angular2-directives


【解决方案1】:

语法

*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和of的区别,文中提到如下:

NgFor 相当于 Angular 中的 for...of 语句,循环遍历一个可迭代对象并一个一个地获取它的每个值。还有 for...in 语句,它会迭代对象的可枚举属性,但没有 Angular 与之等效,所以让我们做一个。

【讨论】:

    【解决方案2】:

    在 JavaScript 中

    for...in 语句,而是迭代对象的可枚举属性

    for...of 语句循环遍历一个可迭代对象,一个接一个地获取其每个值

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 2018-10-13
      • 2018-06-01
      • 2018-04-25
      • 2017-05-07
      • 2016-09-17
      • 2017-05-24
      • 2018-03-23
      • 2016-10-15
      相关资源
      最近更新 更多