Reputation: 399
I'm using Angular 4 to build an app that displays a list of books with title, description and their rating as hearts like the following:
<h2>{{book.title}} <small *ngFor="let h of hearts">❤</small></h2>
In order to get the right number of hearts I created this getter
get hearts() {
if (this.book.rating < 0) {
return new Array(0);
}
return new Array(this.book.rating);
}
For the initial set of books this works quite well. But when I add a new item to the array of books only one heart is displayed. All the other properties however are set correctly. As soon as I change something, also the hearts get updated and are displayed correctly.
Any guesses what I'm doing wrong?
Upvotes: 0
Views: 1006
Reputation: 58099
<small *ngFor="let item of [1,2,3,4,5].slice(5-book.rating)">❤</small>
Upvotes: 0
Reputation: 304
I think the problem might have to do with the component LifeCycle. It's possible that the template gets built before your data gets finished loading...(before book.rating value is set). You could try putting a call to get hearts inside an ngOnInit() method to make sure it gets refreshed.
Also, Deborah Korata has a very interesting way of showing a "5 star" rating for product listings in her course called "Angular: Getting Started" on Pluralsight. (http://www.pluralsight.com). She put the rating inside it's own component. And then puts it in as a select tag:
<star-rating></star-rating>
The component template looks like this:
<div class="crop" [style.width.px]="starWidth" [title]="rating">
<div style="width: 86px">
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
</div>
</div>
The cool thing about this approach is that it actually can show half stars / percentages of stars instead of just whole stars for ratings that are 3.5 or the like.
Upvotes: 1