簡體   English   中英

如何使用ngFor在Angular中循環未知數量的嵌套json object?

[英]How to loop through unknow number of nested json object in Angular with ngFor?

我正在嘗試顯示來自此 json 的所有回復:

https://www.reddit.com/r/AskReddit/comments/k8w43d/people_with_the_last_name_pepper_who_have.json

因此,根據即時加載的帖子和回復,我的孩子數量會有所不同。 我怎樣才能循環遍歷它,直到我到達帶有孩子的最后一個回復(body [2] .data.children)?

像這樣:

<div class="replies-box" *ngFor="let reply of comments.body[1].data.children">
       <div class="reply-header">
            <p class="reply-author"><b>From</b> : {{ reply.data.author }}</p>
            <p class="reply-send"><b>Send</b> : {{ this.getDateReply(reply.data.created_utc) }}</p>
       </div>
       <div class="text-first-reply" [innerHTML]="this.getHtmlDecode(reply.data.body_html)">
         
       </div>
</div>

我只有第一級回復,有沒有辦法簡單地遍歷它們? 提前致謝。

只需在 ng-container 的幫助下在 ngFor 中使用 ngFor(不會創建額外的 dom 元素)

 <div class="replies-box"> <ng-container *ngFor="let commentBody of comments.body"> <ng-container *ngFor="let reply of commentBody.data.children"> <div class="reply-header"> <p class="reply-author"> <b>From</b>: {{ reply.data.author }} </p> <p class="reply-send"> <b>Send</b>: {{ this.getDateReply(reply.data.created_utc) }} </p> </div> <div class="text-first-reply" [innerHTML]="this.getHtmlDecode(reply.data.body_html)"> </div> </ng-container> </ng-container> </div>

我會使用遞歸類型的方法。

開發一個app-comment組件,如果 comment 有子組件,則循環遍歷子組件並顯示app-comment 這樣它就會循環評論直到沒有更多的孩子

<div *ngIf='comment'>
  <span *ngIf='comment.kind; else showComment'>Kind: {{ comment.kind }}</span>
  <ng-template #showComment>
    <span>{{ comment }}</span>
  </ng-template>
  <div>
   <app-comment *ngFor='let child of comment.data?.children' [comment]='child'> </app-comment>
  </div>
</div>

請參閱此示例插圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM