Angular中*ngFor循环对比当前与前一项rating时出undefined错误求助
问题原因与解决方案
错误根源
- 你在
*ngIf条件里写的item[b-1]是核心问题:item是当前循环迭代出的单个对象,不是原数据数组,用数组索引[b-1]去访问单个对象的属性,必然返回undefined,触发报错。 - 要获取前一个元素,得从原数据数组
s_1.comments[0]里取,而非当前的item对象。
修正后的代码
把*ngIf的条件修改为:
*ngIf="b > 0 && item.rating > s_1.comments[0][b-1].rating"
完整修正后的代码片段:
<ng-container *ngFor="let item of s_1.comments[0]; index as b"> <article class="message is-small is-size-6" > <div class="header {{item.type}}"> {{item.type | stringyfy:'_' | titlecase}} <div class="text">{{item.mood}}</div> </div> <div class="body" *ngFor="let comment of item.comments"> {{comment.text}} </div> </article> <article class="message " *ngIf="b > 0 && item.rating > s_1.comments[0][b-1].rating;"> <div class="message-header"> </div> <div class="message-body" > Mood All Year </div> </article> </ng-container>
额外优化建议
可以把s_1.comments[0]赋值给组件类里的变量(比如commentsList),模板直接使用该变量,避免重复访问深层属性,代码更简洁:
组件类中添加:
commentsList = this.s_1.comments[0];
模板修改为:
<ng-container *ngFor="let item of commentsList; index as b"> <!-- 原有内容不变 --> <article class="message " *ngIf="b > 0 && item.rating > commentsList[b-1].rating;"> <!-- 原有内容不变 --> </article> </ng-container>
内容的提问来源于stack exchange,提问作者allforthenoob
相关产品推荐
相关产品推荐

