【发布时间】:2021-09-20 17:17:28
【问题描述】:
我有一个组件可以加载一些带有 id 的项目 单击每个项目后,通过传递基于 id 返回数据的 item-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);
}
【问题讨论】: