【问题标题】:Load dynamic data on click inside nested ngFor Angular在嵌套的 ngFor Angular 内单击时加载动态数据
【发布时间】: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);
}

【问题讨论】:

    标签: angular nested ngfor


    【解决方案1】:

    您为所有行共享相同的“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);
    }
    ....
    

    【讨论】:

    • 一个帖子可以有多个 cmets,我想显示所有这些,而不仅仅是一个
    • 使用此解决方案,您将获得每个帖子的所有评论(任何帖子,所有它的 cmets)。你试过代码了吗?
    • 工作得很好,我最初错过了 loadComments() 函数。谢谢 Juan
    • 不客气!我很高兴它有帮助!
    猜你喜欢
    • 2020-08-13
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2018-10-13
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    相关资源
    最近更新 更多