Angular 5 – Ratings with charts

Hi Friends,

This is a sequel to my previous post about bringing charts into Angular 5 apps with ngx-charts. In this post let’s see how to build a cool ratings chart that updates realtime (Firestore duh!).

I assume you already have a copy of the (previous repo’s) code. If not kindly grab it from here.

Let’s begin.

 

Code for this post is available – here.

Now that we have a basic understanding of how to bring in charts in our app, let’s move on and try to create a simple real-time rating system based on the entries we stored in our firestore collection.

Open up app.component.ts file and modify it as shown below.

This will introduce a horizontal bar chart in your app now (in place of the pie chart).

Now open up app.component.ts and modify it as shown below.

Whoa., that’s a large amount of code right there.. Let’s break this down.

Saving the data and pulling it back is the same as the previous post. The only difference is that we are counting the number of ratings received under each entry (5 being the highest and 1 being the lowest) and storing it in a var called ratingsCount.

Now in the next step I am simply assigning weightage to each rating that I receive, for eg., 5 is the highest rating one can give in a vote, so I am assigning it 5 points , 4 points for a 4 rating and so on..

So now let’s assume a product has received 3 five-star votes, and two 3 star votes. So the rating would be

3 * 5 + 2 *3 = 21

Divide it by the total number of votes(5). So the rating would be 4.2

This is a simple average rating algorithm. This is what we have done in app.component.ts file. Now run the app. If everything goes fine, you would see something like this.

five

Now try adding some entries using the form above and you would see that your rating get’s changed real time along with the chart as well.

Cool.

As, I said in my previous post, charts can be used to represent a large amount of data in a concise way that could be understood with single glance. Hence the number of use cases is large. Here we have seen one such use-case.

Hope his helped you guys. If you found it helpful, kindly share it with someone and help them too.

Thanks for reading. Peace.. :)

 

 

Liked it? Take a second to support admin on Patreon!