【问题标题】:ngFor in custom componentngFor 在自定义组件中
【发布时间】:2019-02-08 08:11:31
【问题描述】:

我在 Ionic v3 中处理一个自定义组件,我正在尝试使用 ngFor。

在我的 .ts 文件中,我的 ngOnInit 中有这个:

this.nb_stars = [];

for(let i=1; i<=4; i++) {
   this.nb_stars.push(i);
}

在我的 .html 中我有这个:

<div *ngFor="let star in nb_stars">
    test
</div>

但我有这个错误:

未捕获的错误:模板解析错误:无法绑定到“ngForIn”,因为 它不是“div”的已知属性。 (" --> ]*ngFor="在 nb_stars 中测试">

"): ng:///ComponentsModule/CompStarsComponent.html@3:5 属性 嵌入模板上的任何指令均未使用绑定 ngForIn。

确保属性名称拼写正确且所有 指令列在“@NgModule.declarations”中。 (" --> [错误->]

如果有人可以帮助我。

【问题讨论】:

  • 语法是for of 不是for in
  • 我遇到了与 for of 相同的错误...

标签: angular ionic3 components ngfor


【解决方案1】:

您需要在 ngFor 指令中将 in 替换为 of 以获取值。
基本上of 在我们必须迭代值时使用,in 在我们必须迭代属性时使用。
请在下面找到详细代码:

<!-- Using of, which iterates over values -->
<div *ngFor="let star of nb_stars">

<!-- Using in, which iterate over properties -->
<div *ngFor="let star in nb_stars">

另外根据您收到的错误,您必须在根模块 (app.module.ts) 中导入 CommonModule,如下所示:

import { CommonModule } from "@angular/common";
@NgModule({
    imports: [CommonModule]
})

【讨论】:

  • 谢谢,我忘记了 CommonModule!
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 2018-06-23
  • 2019-06-13
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多