在角度中循环通过常量

  • 本文关键字:常量 循环 angular
  • 更新时间 :
  • 英文 :


我在 components.ts 文件中声明了一个常量,如下所示

dish = DISH;
const DISH = {
id: '0',
name: 'pizza',
image: '/assets/images/ppizza.png',
category: 'mains',
featured: true,
label: 'Hot',
price: '4.99',
comments: [
{
rating: 5,
comment: 'Test1!',
author: 'John',
date: '2012-10-16T17:57:28.556094Z'
},
{
rating: 4,
comment: 'Test2!',
author: 'Paul',
date: '2014-09-05T17:57:28.556094Z'
},
{
rating: 2,
comment: 'birthday',
author: 'Cent',
date: '2011-12-02T17:57:28.556094Z'
}
]
};

我正在尝试使用循环在注释中显示组件中的数据.html ,但我没有得到信息。我在下面尝试:

<div fxFlex="40">
<p><strong>Comments</strong></p>
<mat-list fxFlex>
<mat-list-item *ngIf ="dish">
<p matLine>
<span> {{dish.comments.comment}}  </span>
</p> 
<p matLine>
<span> {{dish.comments.rating}}  </span>
</p>
</mat-list-item>
</mat-list>
</div>

如何显示所有评论和评分? 犯了什么错误?

你需要使用*ngFor指令:

<mat-list fxFlex>
<mat-list-item *ngFor="let comment of dish?.comments">
<p matLine>
<span> {{comment.comment}}  </span>
</p> 
<p matLine>
<span> {{comment.rating}}  </span>
</p>
</mat-list-item>
</mat-list>

在这里,您可以在dish对象内有一个注释列表,因此您可以遍历其中的列表 (dish.comments(:

<mat-list fxFlex>
<mat-list-item *ngFor="let commentObj of dish?.comments">
<p matLine>
<span> {{commentObj.comment}}  </span>
</p> 
<p matLine>
<span> {{commentObj.rating}}  </span>
</p>
</mat-list-item>
</mat-list>

您必须访问 DISH json 中的注释数组并循环访问它。

<mat-list fxFlex>
<mat-list-item *ngFor="let comment of dish?.comments">
<p matLine>
<span> {{comment.comment}}  </span>
</p> 
<p matLine>
<span> {{comment.rating}}  </span>
</p>
</mat-list-item>

最新更新