In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them.

My issue lies in the fact that when I click on one array element, it automatically selects and fills another array element as well. I want to be able to click on just one item and have that data correctly registered without affecting other elements.

The code for the star component I am using as a base can be found in this stackblitz link:

https://stackblitz.com/edit/angular-material-star-rating-kptyy2?file=app%2Fapp%2Fapp.component.html
Below is the code snippet for my star component.

<button mat-icon-button *ngFor="let ratingId of ratingArr;index as i" [id]="'star_'+i" (click)="onClick(i+1)"
        >
  <mat-icon>
    {{showIcon(i)}}
  </mat-icon>
</button>
<mat-error *ngIf="starCount == null || starCount == 0">
</mat-error>

export class StarRatingComponent implements OnInit {
  @Input("rating") private rating = 3;
  @Input("starCount") public starCount = 5;
  @Output() private ratingUpdated = new EventEmitter();

  public ratingArr = [];

  constructor() {

  }

  ngOnInit() {
    for (let index = 0; index < this.starCount; index++) {
      this.ratingArr.push(index);
    }
  }
  onClick(rating: number) {
    this.ratingUpdated.emit(rating);
    return false;
  }

  showIcon(index: number) {
    if (this.rating >= index + 1) {
      return "star";
    } else {
      return "star_border";
    }
  }
}

Additionally, here is how I am trying to display and populate the language data using this component:

<div *ngFor="let language of subCategory.languages; let i = index">
        <div class="col-md-8">
         {{language.name}}
         <app-star-rating [rating]="language.rate" [starCount]="starCount" (ratingUpdated)="onRatingChanged($event)"></app-star-rating>
        </div>
      </div>

  onRatingChanged(rating) {
    this.skills.subCategories.map(test => test.languages.filter(res => {
      console.log(res.name);
      res.rate = rating;
    }));
  }

Answer №1

To incorporate the index from the HTML into the onRatingChanged function, include it along with the event like this:

 <div *ngFor="let language of languages; let i = index">
      <div class="col-md-8">
         {{language.name}}
         <mat-star-rating [rating]="language.rate" [color]="starColor" (ratingUpdated)="onRatingChanged($event,i)"></mat-star-rating>
      </div>
 </div>

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

Tips for incorporating the multiply times async function into mocha tests

I am attempting to utilize the async function foo multiple times in my mocha tests. Here is how I have structured it: describe('This test', () => { const foo = async () => { const wrapper = mount(Component); const button ...

Determine using Javascript or jQuery whether the value of input1 is greater than the value of input2

Ensuring that Value1 is always greater than Value2 in a form submission is crucial. If Value1 becomes greater than or equal to Value2, an error message should be displayed and the form submission should not be processed. Below is the code for the form: & ...

Adding a proptype for a setState method in React components

I am currently developing a reusable component for a project. This particular component includes user and setUser as props, much like the example provided below. const UserComponent = ({ user, setUser }) => { const calcHandler = useCallback(() =& ...

Error: Attempted to search for 'height' using the 'in' operator in an undefined variable

I came across the following code snippet: $('.p1').click(function(){ var num = 10; var count = 0; var intv = setInterval(anim,800); function anim(){ count++; num--; ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

Discovering the element on which the value has decreased - a helpful guide

I am attempting to create a drag and drop feature for simple calculations. Users can drag the UP value and drop it on either BH or OT. The issue I'm facing is that I cannot identify the ID where the user dropped, and the onDrop() function is not work ...

What is the best way to enable a child category on a treeview within a Vue component?

I am working with two vue components. The first component (parent component) looks like this: <template> ... <ul class="filter-category" v-for="list in categories"> <list-category :data="list" :category-id="category ...

Can you build and run a production-ready Vue application on your local system?

After running the npm run build command in my vue project, I placed the dist folder in C:\xampp\htdocs\ and launched the apache server to test the app on my local machine. However, when I try to access http://localhost/dist/index.html in my ...

Best Practices for Angular (2) Form Validation on the Server Side

Struggling to implement server-side form validation using Angular 2, specifically with the following setup: A basic form with login and password fields linked to the view via ngForm / ngModel directives Template-based form structure Synchronous validatio ...

Creating an element in react-draggable with two sides bound and two sides open - here's how!

At the moment, I am facing an issue where the element is restricted from moving outside of the container with the class of card-width-height. My goal is to have the right and bottom sides bounded within the container while allowing the element to move beyo ...

Having trouble transmitting POST values through AJAX requests

I am facing an issue with two separate files, bargraph.html and data.php. Here is the content of bargraph.html: <form method="POST" name="dataform" action=""> <select name="data1" id="data1-value"> <option value="DateRecorded">Dat ...

What are some ways to leverage the window object within Angular 2?

I attempted to include the following code in order to access a window object in angular 2: @Component({ selector: 'app-slider', templateUrl: './slider.component.html', styleUrls: ['./slider.compo ...

What functions do the accelerometer, gyroscope, and picture-in-picture serve in the HTML code for embedding a YouTube video?

After successfully uploading a video on Youtube, you will be provided with the following HTML code for embedding: <iframe width="560" height="315" src="https://www.youtube.com/embed/UF8uR6Z6KLc" frameborder="0" allow="accelerometer; autoplay; encrypt ...

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...

I am attempting to input the form data, but all I see on the console is "null" being printed

I am facing an issue where the console.log(data) statement is printing null on the console. I am trying to send the form data (with id "myform") to a Java backend post method, but for some reason the code is not functioning correctly. Can anyone identify ...

Empty jQuery $.ajax value after post

I'm encountering an issue where my code's post value appears to be empty. I have attempted to echo the key and value using a foreach loop, but it only shows "0 Array." This is what my code looks like: <script type="text/javascript"> $(doc ...

Experience the Firefox nightmare with a fixed background-attachment!

I've been struggling with a puzzling issue all day, and I'm hoping that someone with more expertise can help me solve it. As I work on updating the design of my website, I've encountered what seems to be a bug specific to Firefox. I've ...

Node.js and Express: Delegate routes to different endpoints for handling by the Single Page Application, instead of just the root route

I have my node.js/Express server configured to host my Vue.js single page application from the root URL path (localhost:3333) within the public folder. When navigating through my app, everything works smoothly thanks to the vue.js History API handling all ...

Decode JSON and generate a user-friendly Array

My aim is to extract and organize the JSON data received from an external API into a custom array. However, I am encountering two challenges: I'm struggling to access the value labeled #2 under "Meta Data". If I want to extract the first array n ...

"Navigate to another screen with the FlatList component upon press, displaying specific

I've created a flatlist of countries with a search filter using an API. I need help implementing a feature where clicking on a country's name in the list redirects to a screen that displays the country's name and number of cases. The screen ...