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

Angular嵌套ngFor中点击加载动态数据仅在对应条目下展示的问题

问题原因
  • 组件内仅声明了一个全局共享的comments数组,所有条目绑定的是同一个数据源,只要数组更新,所有条目的评论区都会同步渲染数据,因此出现全条目显示的问题。
  • 没有标记当前处于激活展开状态的条目,无法区分需要单独展示评论的目标条目。
修复方案

1. 修改 timeline.component.ts

删除全局comments数组,新增激活id标记和评论缓存对象,避免重复请求:

@Input() posts: any = [];
// 存储当前点击激活的帖子id
activePostId: number | null = null;
// 键为帖子id,值为对应评论数组,缓存已加载的评论
commentMap: Record<number, any[]> = {};

constructor(private dataService: DataService) { }

loadComments(id: number){
  this.activePostId = id;
  // 已加载过的评论直接复用缓存,无需重复发请求
  if(this.commentMap[id]) return;
  this.dataService.getComments(id).subscribe(comments => {
    this.commentMap[id] = comments;
  });
}

2. 修改 timeline.component.html

添加显式判断,仅当前条目为激活状态时才渲染对应评论:

<ul>
    <li *ngFor="let post of posts">
       <button (click)="loadComments(post.id)">{{post.title}}</button>
       <ul class="comment-holder" *ngIf="activePostId === post.id && commentMap[post.id]">
            <li *ngFor="let comment of commentMap[post.id]">
                {{comment.body}}
            </li>
       </ul>
    </li>
</ul>
可选优化

如果需要实现点击已激活按钮收起评论的效果,修改loadComments逻辑即可:

loadComments(id: number){
  // 点击已激活的条目直接收起评论
  if(this.activePostId === id) {
    this.activePostId = null;
    return;
  }
  this.activePostId = id;
  if(this.commentMap[id]) return;
  this.dataService.getComments(id).subscribe(comments => {
    this.commentMap[id] = comments;
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:09:03