What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  projectRating = 2;
  projectRatingArr=[];
  animeArr=[];
  counter;
  isHalf = false;
  ngOnInit() {
    this.updateStars();
     this.getArrayValues(0);
  }
  updateStars() {
    for(let i=0; i<this.projectRating;i++){
      this.projectRatingArr.push(i)
    }
    console.log(this.projectRatingArr);
  }
 getArrayValues(index) {
    setInterval(() => {
      if(index == this.projectRatingArr.length)
        return;
      this.animeArr.push(this.projectRatingArr[index]);
      index++;
    }, 50);
  }
}

html

<div class="wrapper">
    <div class="item">
        <div *ngFor="let i of [0,1,2,3,4]">
            <div class="fav fav-star-default "></div>
        </div>
    </div>
  <div class="item">
        <div *ngFor="let i of animeArr;last as isLast">
            <div class="fav fav-star is-animating"></div>
        </div>
    </div>
</div>

I attempted to keep track of a variable named isHalf and whenever the Project Rating is 4.5 or another value ending in .5, I need to target the last star in the ngFor loop and only display the left half of that element.

While working on this, I have hit a creative roadblock.

My goal is to change the star to a half star if the rating includes a .5.

I experimented with adding a class to hide it but the remaining half appears empty.

Any assistance would be greatly appreciated.

Here is the link to my stackblitz: https://stackblitz.com/edit/angular-joszev

Answer №1

For the desired outcome, follow these steps to incorporate two additional divs - one displaying a full star and the other a half star:

  1. Generate two stars with a condition to only show when the rating is 0.5

    <div class="item">
      <div *ngFor="let i of animeArr;last as isLast">
        <div class="fav fav-star is-animating" [ngClass]="{'isHalf': isHalf}"></div>
        <div class="halfstar1" *ngIf="isHalf">&#x2605;</div>
        <div class="halfstar2" *ngIf="isHalf">&#x2605;</div>
      </div>
    </div>

  1. Apply the following CSS styles for those two stars

     .halfstar1 {
        position: absolute;
        top: -6px;
        right: 15px;
        width: 34px;
        font-size: 40px;
        color: #666;
        overflow: hidden;
        z-index: 1;
        }
    
        .halfstar2 {
            position: absolute;
            top: -6px;
            right: 32px;
            width: 17px; 
            font-size: 40px;   
            color: rgb(252, 173, 3);
            overflow: hidden;
            z-index:2;
        }

See the working code for reference - https://stackblitz.com/edit/angular-krmrsj?file=src/app/app.component.css

Note: Adjust the positioning based on your layout, and this code specifically caters to the last value being 0.5. For other decimal values, the right value may need adjustments.

Answer №2

To represent different values in your array, you can use:

1 = full star; 0.5 = half star;

In your HTML, include an [ngClass]='colorStar(i)'. This function will determine the appropriate class based on the value, allowing you to style the stars with CSS.

For example: http://jsfiddle.net/Ah8uZ/

<div class="star gold">&#x2605;</div>
<div class="star gold-gray">&#x2605;</div>
<div class="star gray">&#x2605;</div>



.star {
    display: inline-block;
    width: 20px;
    text-align: center;
}
.star.gold { color: gold; }
.star.gold-gray { color: gray; }
.star.gold-gray:after {
    display: inline-block;
    color: gold;
    content: '\2605';
    position: absolute;
    margin-left: -16px;
    width: 8px;
    overflow: hidden;
}
.star.gray { color: gray; }

Answer №3

<span class="material-icons filled iconRatingStar" *ngFor="let item of [0,1,2,3,4]; let i = index">
        {{(i + 1) <= value? 'star_rate' : (value % 1 !==0 && (value | round)===(i + 1))?'star_half':'star_outline'}} 
    </span>

'value' represents the rating number, with a value of 3.5

RoundPipe has been added to achieve rounding functionality

@Pipe({ name: 'round' }) export class RoundPipe {
transform(input: number) {
    return Math.round(input);
}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating uniform table column widths within a flex container with dynamic sizing

I am working on designing a navigation system for my website using a table inside a flexbox. I want to ensure that the table columns have equal width and can scale dynamically. Additionally, I aim to wrap the text in the data cells without changing the cel ...

Utilizing React Selector: Propagating the onChange Event Up Two Components

Struggling to pass an onChange event from React selector through two components back up to the parent App. The issue is that e.target.value is coming back as undefined, indicating that the event might not be returning properly. Can someone pinpoint what&ap ...

Choose your location with React: Country -> Province/State -> City?

It seems to be a common need for people to have a feature where selecting a country would then filter down the provinces or states available for that country, and then from there, narrow down to city selections. I've been searching NPM for a solution, ...

Leveraging jQuery event listeners within a Javascript class initialization

Recently delving into OOP in JavaScript, I've been revamping some of my old code to make it more reusable. Instead of leaving them as inline scripts, I decided to encapsulate them within JavaScript classes. Here is an example of one of my classes: ...

Unable to save the ID of an element into a jQuery variable

I am currently working on a project that involves an unordered list with anchor tags within it. I am trying to access the id of the li element that is being hovered over, but for some reason, the alert is returning undefined or nothing at all. Here is the ...

React components featuring Material UI icons

I'm in need of assistance. I am looking for the Material UI icons, but I can't seem to find any information on how to obtain them. https://i.stack.imgur.com/FAUc7.jpg ...

Issue with Bootstrap 4 navbar z-index not functioning as expected

Hello, I am struggling to place my navbar on top of an image using bootstrap 4. I have set the CSS properties for both elements, but it doesn't seem to be working. Here is the code I am using: <header> <nav class="navbar navbar-toggl ...

Discovering text on a webpage and extracting its XPath or CSS using Selenium and Java

Imagine a scenario where there is a page displaying various items on a table that changes in both order and quantity randomly. The task at hand is to locate a specific item labeled "Itemx" by its text, extract its XPath or CSS, and then use it in another ...

Using React and Material-UI: Implementing button functionality to call another class using hooks in the main App component

Just starting out with React/MUI and currently working on different components for a website, so the UI is not a priority at the moment. Encountering an issue when trying to create a button that links to the Sign Up page (similarly for Sign In): Error: ...

html2canvas encountered a CORS error when trying to retrieve images from an external domain

I have been attempting to export a react component as a PDF file. Here are the steps I have followed: Converting the component into an image using html2canvas Creating a PDF document Attaching the image to the PDF The component contains images with URLs ...

Retrieve JSON data from an HTTP request using Node.JS

Hi there, I'm struggling with the Node.js HTTPS request. Basically, I send a request to a server and it responds with a JSON message that I need to parse and save in a variable so I can use it in other functions. let obj=JSON.parse(response); return ...

Encountered an issue with AWS S3: unable to retrieve the certificate from the local issuer

After completing my Protractor test suite execution, I am encountering an error while trying to upload my HTML result file to AWS S3 using JavaScript in my automation script. Can someone assist me in resolving this issue? static uploadtoS3() { con ...

Using Angular to send all form data to the API endpoint

Please bear with me as I am new and may ask small or incorrect questions. <form > <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:< ...

Having trouble with JavaScript/JQuery not functioning properly in HTML content loaded using the load() method

My goal is to load an input form from a separate file called new_machine.php into my index.php. This form includes an input with a dropdown that retrieves options from a MySQL database and displays them as anchors. The issue arises when I attempt to manipu ...

How to refresh a page in Angular Typescript to wait for HTTP calls from the backend

Looking at the code snippet below: The initial HTTP call retrieves multiple IDs of orderlines (items). For each ID, another HTTP call is made to reserve them. Afterward, the page needs to be updated to display the reserved items. When dealing with a larg ...

Is the Property Decorator failing to substitute the definition?

My code is similar to the following scenario, where I am attempting to replace a property based on a decorator export function DecorateMe() { return function(component: any, propertyKey: string) { Object.defineProperty(component, propertyKey, ...

What is the best way to enable a disabled MUI MenuItem within a table that is being mapped, based on a specific item in the

In my table, I have a mapped object of users: {users.map((user,index) => { <TableRow key={index}> ... The final cell in the table contains a button that is linked to an MUI Menu. One of the menu items should be disabled if a specific aspect of ...

Using Ajax.Updater to run JavaScript code

I've tried numerous online tutorials and examples, but haven't had much success... I'm looking to execute JavaScript from an HTML Response in Ajax. Here's my code snippet: <script src="prototype.js" type="text/javascript"></ ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...