在嵌套的 ngFor 中点击加载动态数据 Angular

Load dynamic data on click inside nested ngFor Angular

我有一个组件可以加载一些带有 id 的项目 单击每个项目时,通过传递基于 id 的 returns 数据的项目 ID 来点击另一个 Api 稍后我想在我单击的项目下方显示此数据 但不幸的是,数据被添加到每个项目下,我该如何控制?

这是我的代码

//app.component.ts
  ngOnInit(){
     this.dataService.getPosts().subscribe(posts => this.posts = posts);        
  }

//app.component.html
<app-timeline [posts]="posts"></app-timeline>

//timeline.component.html
<ul>
    <li *ngFor="let post of posts">
       <button (click)="loadComments(post.id)">{{post.title}}</button>
          <ul class="comment-holder">
            <li *ngFor="let comment of comments">
                {{comment.body}}
            </li>
          </ul>
    </li>
</ul>

//timeline.component.ts
 @Input() posts: any = [];
 comments: any = [];

 constructor(private dataService: DataService) { }

loadComments(id){
  this.dataService.getComments(id).subscribe(comments => this.comments = comments);
}

您对所有行共享同一个 'commemts' 数组。你必须换一种方式去思考。

但是,如果 'post' 的 'id' 是一个数字,而您想要轻松更改,也许这可行:

//timeline.component.html
<ul>
    <li *ngFor="let post of posts">
       <button (click)="loadComments(post.id)">{{post.title}}</button>
          <ul class="comment-holder">
            <li *ngFor="let comment of comments[post.id]">
                {{comment.body}}
            </li>
          </ul>
    </li>
</ul>

//timeline.component.ts
...
loadComments(id){
  this.dataService.getComments(id).subscribe(comments => this.comments[id] = comments);
}
....