[英]How to get ngFor data getting the id in another ngFor - Angular5
I have a array of objects with id, and I need pass this id in other array; 我有一个ID为ID的对象数组,我需要在另一个数组中传递ID。 Example:
例:
product = [
{ id: 1, name: teste }, { id: 2, name: teste 2 }
]
comment = [
{product_id: 1, comment: lorem ipsum }
]
I'm need a ngFor to receive a product and commentary 我需要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>
Would work (inefficiently). 会(效率低下)。 It would be better architecture to join the
comment
to the product
model in a service or similar for when you need to do this again. 将
comment
到服务或类似product
中的product
模型中是更好的体系结构,以备您需要再次执行此操作时使用。
I believe something like: 我相信类似:
<div *ngFor="let prod of product">
{{prod.name}}
<div class="comments">
<div *ngFor="let comment of commentsOfProd(prod.id);">
{{ comment.comment }}
</div>
</div>
</div>
Where method commentsOfProd(id) would return array of filtered comments for the product. 其中,方法commentsOfProd(id)将返回该产品的过滤后评论数组。
Or a little more simply only in template: 或者仅在模板中简单一点:
<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>
It is not a rocket science with these directive. 这些指令并不是一门火箭科学。 It works almost same as normal For or If in the code.
它的工作原理与代码中的常规For或If几乎相同。 So the second example is basically just cycle in cycle with a condition.
因此,第二个示例基本上只是带有条件的循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.