You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17迁移后模板报NG5002错误:@for循环表达式格式不符

解决Angular 17中@for循环的NG5002语法解析错误

Angular 17启用的新控制流语法里,@for循环有严格的格式要求,必须匹配" of "的模式,出现NG5002错误就是因为写法不符合规范,按以下步骤修正:

  • 替换循环关键字:将模板中所有@for循环里的in替换为of,这是最常见的错误原因。
  • 确保track语句完整:Angular 17要求@for必须指定跟踪标识,避免重复渲染。可以用集合项的唯一属性(如item.id),或者用$index作为临时跟踪值。
  • 排查拼写错误:检查是否把of写成off等错误拼写,或是表达式中存在多余符号、格式混乱。

错误与正确写法对比

错误示例:

@for (product in productList; track product.id) {

{{product.name}}

}

正确示例:

@for (product of productList; track product.id) {
  <p>{{product.name}}</p>
}

临时集合的写法

如果循环的是临时数组字面量,可使用$index跟踪:

@for (tag of ['angular', 'frontend', 'typescript']; track $index) {
  <span class="tag">{{tag}}</span>
}

内容的提问来源于stack exchange,提问作者Amirreza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:32:03