Angular2使用ngFor渲染article/div时出现'ngForFor'未知属性错误
解决Angular中ngFor的"无法绑定到'ngForFor'"错误
嘿,这个问题我之前也踩过坑,主要是两个地方出了问题,咱们一步步来搞定:
1. 修正ngFor的核心语法错误
你代码里的ngFor用错了关键字!Angular的*ngFor指令要求用of来遍历集合,而不是for——这是直接触发报错的原因。
你的原代码片段:
<section class='mycontainer'> <article *ngFor="let numberStep for steps; let i = index" [ngClass]="article + i"> <div class='line'...
修正后的代码:
<section class='mycontainer'> <article *ngFor="let numberStep of steps; let i = index" [ngClass]="'article' + i"> <div class='line'>...</div> </article> </section>
另外提一句[ngClass]这里,我给article加了单引号,不然Angular会把它当成组件变量解析,大概率会报"找不到变量article"的错误,加引号后才会按字符串和索引拼接处理。
2. 确认CommonModule已正确导入
如果语法改完还是报错,就要检查组件所在的模块有没有导入CommonModule——ngFor、ngIf这类基础结构指令都属于这个模块:
- 如果是根模块(AppModule):直接导入
BrowserModule就行,它已经包含了CommonModule - 如果是子模块:必须单独在模块的
imports数组里添加CommonModule
示例模块代码:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // 导入你的目标组件 import { YourComponent } from './your.component'; @NgModule({ declarations: [YourComponent], imports: [ CommonModule // 这一步不能少! ] }) export class YourModule { }
这两步做完,应该就能彻底解决这个"无法绑定到'ngForFor'"的错误啦。
内容的提问来源于stack exchange,提问作者EduBw
相关产品推荐
相关产品推荐

