【问题标题】:Can't declare an object in *ngFor iterator of Angular无法在 Angular 的 *ngFor 迭代器中声明对象
【发布时间】:2018-04-13 01:27:11
【问题描述】:

我正在使用以下代码来迭代一堆自定义控件。因为那些需要知道一些东西,比如结构中的索引和位置,所以我传入一个配置对象来像这样把垃圾放在一起。

<div *ngFor="let thing of stuff; let first=first; let last=last; let index = index;">
  <app-thingy [data]="thing"
              [config]="{first:first,last:last,index:index}">
  </app-thingy>
</div>

我希望代码更紧凑,而且let this 和let that 似乎是一个非常重复的语法。所以我想我可以像这样在迭代标签中直接创建对象。

<div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
  <app-thingy [data]="thing"
              [config]="config">
  </app-thingy>
</div>

但是,Angular 对此大喊大叫,声称 config 定义中的大括号是无效语法。

未捕获的错误:模板解析错误:
解析器错误:[let thing of stuff; 中的第 45 列出现意外的令牌 {、预期的标识符、关键字或字符串让 config={first:first,last:last,index:index};] in
...

]*ngFor="let thing of stuff; let config=

据我所知,语法是错误的但是我不明白为什么。有人可以解释一下为什么这两个样本不等价吗?

我注意到在 HTML 标记中使用 new MyType(...) 也不起作用,但这显然是设计使然。但是,这是一个匿名对象(类型为any)所以我有点疑惑。

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    这是错误的

    <div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
      <app-thingy [data]="thing"
                  [config]="config">
      </app-thingy>
    </div>
    

    因为 first:first,last:last,index:index 引用循环条件,所以它们不作为对象处理。您可以将其理解为 javascript 中的 for 循环,例如

    for(let i=0; i<somelength ;i++){}
    

    like i=0 等于 first:first 和 somelength 等于 last:lasti as index:index。它们不能像上面那样通过。

    【讨论】:

    • 所以如果没有一遍又一遍的let,就没有办法让它们进入[config]?在我看来,这是相当冗长的语法。
    • 顺便说一句,我没有对你投反对票,也没有对@sajeetharan 投反对票。
    • 是的,你可以
    【解决方案2】:

    您不能在 component.html 中使用 let 声明对象

    错误

    <div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
    

    相反,您可以在 ts 中创建对象并在 HTML 中传递它

    【讨论】:

    • 这需要两个后续问题。首先是如何 - 我无法访问 TS 文件中的 firstlastindex,可以吗?我的印象是这些值是在枚举过程中生成的,因此在组件的逻辑中不可用。第二次跟进将是为什么 - 我想知道设计背后的基本原理。
    猜你喜欢
    • 2018-08-31
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2017-11-29
    • 2020-08-15
    • 2020-01-03
    相关资源
    最近更新 更多