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

Angular中*ngFor循环访问前一个对象值时条件不生效问题排查

问题排查与解决方案

核心问题可能出在以下几个方面:

  • 循环目标错误
    你提供的arr_1是二维数组(外层数组包裹着评论数组),如果你的*ngFor直接循环arr_1,每一项都是整个评论数组而非单个带rating的对象。此时拿当前项和前一项比较,本质是在比较两个数组对象,永远不会满足rating大小的条件。

  • 未处理索引边界与前项获取
    在*ngFor中比较当前项和前一项时,必须先确保当前索引i > 0(第一个元素没有前一项),否则arr[i-1]会返回undefined,undefined.rating为undefined,和数字比较永远不成立。

  • 数组引用错误
    如果模板中误用了未正确赋值的数组变量,或者数组数据未完成初始化就渲染,也会导致条件判断失效。


正确代码示例

情况1:循环s_1.comments(一维数组)

<article *ngFor="let comment of s_1.comments; let i = index">
  <!-- 先判断索引大于0,再比较rating -->
  <div *ngIf="i > 0 && comment.rating > s_1.comments[i-1].rating">
    Mood All Year
  </div>
</article>

情况2:循环arr_1(二维数组)

需要先遍历外层数组,再遍历内层评论数组:

<div *ngFor="let commentList of arr_1">
  <article *ngFor="let comment of commentList; let i = index">
    <div *ngIf="i > 0 && comment.rating > commentList[i-1].rating">
      Mood All Year
    </div>
  </article>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:57:18