自定义组件中的 ngFor

ngFor in custom component

我在 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>

但是我有这个错误:

Uncaught Error: Template parse errors: Can't bind to 'ngForIn' since it isn't a known property of 'div'. (" --> ]*ngFor="let test in nb_stars">

"): ng:///ComponentsModule/CompStarsComponent.html@3:5 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". (" --> [ERROR ->]

如果有人能帮助我。

您需要在 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]
})