Reputation: 443
how can i show "comment" of this json data in my template ???
(this json comes from ngFor data)
{
"product_id": 2,
"author": 1,
"category": 2,
"title": "python",
"description": "python desc",
"filepath": null,
"price": "50000",
"created_date": "2018-01-28T03:30:00+03:30",
"updated_date": "2018-01-28T03:30:00+03:30",
"product_ratings": {
"p_id": 2,
"commenter": 1,
"comment": "very nice totorial",
"rating": 5,
"created_date": "2018-02-05T03:30:00+03:30"
}
}
i did like below
my component.html
<ul>
<li *ngFor="let data of products">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="http://lorempixel.com/output/technics-q-c-200-200-7.jpg">
</div>
<div class="card-content">
<div>{{ data.title }}</div>
<div>{{ data.description }}</div>
<div *ngFor="let rate of data.product_ratings">{{ rate.comment }}</div>
</div>
</div>
</li>
</ul>
but i get this error:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
when i trying to access comment with :
{{ data.product_ratings.comment }}
i will get
TypeError: Cannot read property 'comment' of null
in browser console
Upvotes: 0
Views: 3386
Reputation: 68665
Your product_ratings
is just an object, not array. You can use simple property access to it instead of *ngFor
<div>{{ data.product_ratings?.comment }}</div>
Upvotes: 1
Reputation: 593
You can't do a ngFor
loop in the object properties.
Instead of this line
<div *ngFor="let rate of data.product_ratings">{{ rate.comment }}</div>
You can do like this
<div>{{ data.product_ratings.comment }}</div>
NgFor only loops through arrays, you have got an object so you can access its properties using the simple dot syntax.
So you just need to check the product rating available before you bind it. You only getting this because sometimes you don't have data in your ratings
Like this
<div *ngIf="data.prodduct_ratings">{{ data.product_ratings.comment }}</div>
If you had an array of product_rating
then this syntax would be helpful.
Hope that helps.
Upvotes: 1
Reputation: 58593
As data.product_ratings
is not array but just a json
, so that is not Iterables , coz of that you are getting that error.
So you need to remove :
*ngFor="let rate of data.product_ratings"
and change
{{ rate.comment }}
to {{ data.product_ratings.comment }}
Upvotes: 1