簡體   English   中英

如何獲取ngFor數據以獲取另一個ngFor中的ID-Angular5

[英]How to get ngFor data getting the id in another ngFor - Angular5

我有一個ID為ID的對象數組,我需要在另一個數組中傳遞ID。 例:

    product = [
      { id: 1, name: teste }, { id: 2, name: teste 2 }
    ]

    comment = [
      {product_id: 1, comment: lorem ipsum }
    ]

我需要ngFor才能收到產品和評論

<div *ngFor="let prod of product">
 {{prod.name}}
 <div class="comments">
 /* i need pass comment object from product_id == prod.id /*
 how do I do that?
 </div>
</div>
<div *ngFor="let prod of product">
  <div *ngFor="let c of comment">
    <span *ngIf="c.product_id === prod.id">{{ c.comment }}</span>
  </div>
</div>

會(效率低下)。 comment到服務或類似product中的product模型中是更好的體系結構,以備您需要再次執行此操作時使用。

我相信類似:

<div *ngFor="let prod of product">
  {{prod.name}}
  <div class="comments">
    <div *ngFor="let comment of commentsOfProd(prod.id);">
       {{ comment.comment }}
    </div>
  </div>
</div>

其中,方法commentsOfProd(id)將返回該產品的過濾后評論數組。

或者僅在模板中簡單一點:

<div *ngFor="let prod of product">
 {{prod.name}}
  <div class="comments">
    <div *ngFor="let comment of comments">
       <div *ngIf="comment.product_id == prod.id">
         {{comment.comment}}
       </div>
     </div>
   </div>
 </div>

這些指令並不是一門火箭科學。 它的工作原理與代碼中的常規For或If幾乎相同。 因此,第二個示例基本上只是帶有條件的循環。

暫無
暫無

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

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