Tips for implementing multiple Angular components within a loop

I am currently working on a pop-up notification system for displaying all unrated purchase order deliveries. However, I am facing a challenge in implementing *ngFor loop to iterate through the orders.

My system allows users to rate their item order deliveries by accessing a rating page for each order. This process involves using a custom Star Rating Component.

The issue arises when I try to remind users about pending ratings through a notification panel. The panel uses a modal with repeated rating components to prompt users to rate their orders immediately.

While looping through all the unrated orders, I encounter a problem where changing the rating of one order affects the ratings of all other orders. How can I resolve this issue?

<ng-container *ngFor="let task of unratedOrders; let i = index">
                            <div class="col-md-3">
                                <div class="card">
                                    <div class="card-body r-wrapper__body">
                                        <div>
                                            <div class="avatarx">

                                            </div>
                                            <div class="header">
                                                <h3 class="card-title">Rate task {{task.orderId}}</h3>

                                            </div>
                                        </div>
                                        <div class="star-rating-size">
<!-- The rating component is here -->
                                            <star-rating id="{{task.orderId}}-rating-component" (ratingChange)="changeRating($event)" [controlIndex]="i" [ratings]="ratings" [(rating)]="supplierRating.ratingId"></star-rating>
                                        </div>
                                        <div class="r-info">
                                            <div class="r-info__icon">
                                                <i class="fa fa-info-circle" aria-hidden="true"></i>
                                            </div>
                                            <p>
                                                <span *ngIf="selectedRating"><b>{{selectedRating?.ratingHeader}}</b> - {{selectedRating?.ratingDesc}}</span>
                                            </p>
                                        </div>
                                        <textarea class="r-comment" name="" placeholder="Write a short comment.." id="" cols="30" rows="2" [(ngModel)]="supplierRating.description"></textarea>
                                        <button type="button" class="btn btn-sm" (click)="changeETA(task)">Change ETA</button>
                                        <button type="button" class="btn btn-primary btn-sm" (click)="submitRating($event)">Submit rating</button>
                                    </div>
                                </div>
                            </div>
                        </ng-container>

PS: Following is the component

Moreover, the ratings that I pass to the component represent the data for the rating loop, typically consisting of 5 rating options passed as an object. This data is used to render 5 stars in the component.

<fieldset class="rate" id="rate-{{controlIndex}}" [class.readonly]="readonly">
    <ng-container *ngFor="let star of ratings; let i = index">
        <input type="radio" id="rating-{{ratings.length-i-1}}-{{controlIndex}}" name="rating-{{controlIndex}}" [checked]="(star.id == rating)" />
        <label [class.half]="(i%2)==1" for="rating-{{ratings.length-i-1}}-{{controlIndex}}" (click)="updateRating(star.id)"></label>
    </ng-container> 
</fieldset>

https://i.sstatic.net/DmBmR.png

Despite implementing various techniques like inserting unique IDs, the issue still persists!

Answer №1

I'm not sure if you actually need to utilize your component. If not, there is a module available from ng-bootstrap for star rating that is extremely user-friendly. You can find more information and examples here. Plus, you can easily store your ratings in an array.

Answer №2

Is it possible that instead of [ratings]="ratings", it should actually be [ratings]="task.ratings"? It seems like in this loop, you should assign the rating value to the current element being iterated. This could be why all values are changing when one is altered.

Answer №3

It's unclear to me how you are updating your ratings value. It appears that you are binding to the same ratings in every <star-rating> element, but because of the custom directive being used, the internal workings are unknown to me. This situation seems questionable.

Answer №4

Perhaps there is an issue with the star rating component you are using. It seems like there may not be any differentiation in id types when adding ratings.

Providing code would be beneficial for a more precise analysis.

unratedOrders - [{
orderId:1234
ratings:[{},{}]
}]


<div class="star-rating-size">
    <star-rating #starRating id="{{task.orderId}}-rating-component" (ratingChange)="changeRating($event,task)" [controlIndex]="i" [ratings]="task.ratings" [(rating)]="supplierRating.ratingId"></star-rating>
</div>

changeRating(event, selectedTask) {
    loop through unratedOrders and assign value to selected task
}

Answer №5

It seems like there may be an issue with the star rating component you are using. There could be a lack of id type differentiation when adding ratings, which could be causing the problem. To accurately diagnose the issue, sharing the code would be helpful.

Your code snippet should look something like this:

unratedOrders - [{
orderId:1234
ratings:[{},{}]
}]


<div class="star-rating-size">
    <star-rating [ratings]="task.ratings" (ratingChange)="changeRating($event,task)"  id="{{task.orderId}}-rating-component"  [controlIndex]="i"  [(rating)]="supplierRating.ratingId"></star-rating>
</div>

changeRating(event, selectedTask) {
    loop through unratedOrders and assign value to selected task
}

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

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

Notes on using touch devices with Angular

My goal is to make my Angular application capable of displaying a footnote on mobile devices when text injected with nativeElement.innerHTML is clicked. I attempted to explain this before but feel that I didn't do it justice, so here's another sh ...

Having trouble reading local storage in Angular 2

I have inserted a token into local storage and am attempting to console.log it. Here is my code snippet: ngOnInit(){ console.log('Member Info: ', JSON.parse(localStorage.getItem('LOCAL_TOKEN_KEY'))); } Although this seems correct ...

Only one radio button in Angular2 remains enabled

On a page, I have a set of radio buttons grouped into "Yes" or "No" buttons. Depending on the value of a variable, I want to disable them. However, only the "Yes" button is disabled when initially loading the page. There is also a drop-down that changes ...

The URL "http://packagist.org/p/provider-3.json" was unable to be retrieved due to a bad request error (HTTP/1.1 400 Bad Request)

Encountering a 400 bad request issue when trying to connect over HTTP, despite the package only being installable via HTTP. Attempting to override in composer.json to force HTTPS as suggested by others for a workaround, but that solution doesn't seem ...

Angular 6: Issue TS2339 - The attribute 'value' is not recognized on the 'HTMLElement' type

I have a textarea on my website that allows users to submit comments. I want to automatically capture the date and time when the comment is submitted, and then save it in a JSON format along with the added comment: After a comment is submitted, I would li ...

Setting up NextJs in Visual Studio Code with Yarn

When I used yarn create next-app --typescript to set up a TypeScript Next.js application with Yarn, everything seemed to be working fine with the command yarn run dev. However, Visual Studio Code was not recognizing any of the yarn packages that were added ...

Not sure of the best location to place the subscription for three observables linked with switchMap?

this._authService.loggedInUser$.pipe(switchMap((loggedInUser: LoggedInUser) => { return this._userSerialService.getUserSerial().pipe(switchMap(serial => { return this._usersService.getCurrentUser().pipe(switchMap(currentUser => [lo ...

Angular 6 - Unlocking the Secrets of Filtered Results

I need help accessing the filteredArray in my .ts component. Currently, it is only accessible within the ng-container. <ng-container *ngIf="(userList | filter: 'name' : value) as filteredArray"> <tr *ngFor="let user of filteredArray ...

Receiving an eslint error while trying to integrate Stripe pricing table into a React web application

If you're looking to incorporate a Stripe documentation code snippet for adding a stripe-pricing-table element, here's what they suggest: import * as React from 'react'; // If you're using TypeScript, don't forget to include ...

Tips for updating the class of the body in an Angular 2 and Typescript project

When it comes to managing different classes for the login page versus other pages in an application, there is a need to change the body element's class once the user has logged in. Here is how I am attempting to achieve this: index.html <body [ng ...

Exploring the power of Vue.js reactivity using Object.defineProperty in a TypeScript environment

Currently, I am in the process of developing a TypeScript class to manage form submissions and handle server errors: export default class Form<Model> { private readonly original: Model private changes: Partial<Model> constructor(d ...

Version 4.0 of Electron-React-Boilerplate has encountered an error: The property 'electron' is not recognized on the type 'Window & typeof globalThis'. Perhaps you meant to use 'Electron' instead?

I encountered an error while attempting to call the IPCrenderer using the built-in context bridge. The error message reads as follows: Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Elect ...

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

AG-Grid hierarchical data structure

Transitioning from kendo tree list to ag grid tree data grid, I am facing a challenge. My table data is currently formatted as shown below, but ag grid requires data in the form of a string array of nodes in a tree. How can I adapt or customize my existing ...

Using Promise.all like Promise.allSettled

I am looking to streamline the handling of Promise.allSettled in a more generic way. Currently when using allSettled, it returns a list of both fulfilled and rejected results. I find this cumbersome and do not want to handle it everywhere in my code. My g ...

NPM is lacking in providing sufficient guidance on resolving dependency problems

While attempting to incorporate Typescript into my Gatsby project after the fact, I encountered a cryptic error from NPM: npm ERR! code EOVERRIDE npm ERR! Override for @types/react@* conflicts with direct dependency npm ERR! A complete log of this run can ...

Is it possible to establish a connection between Firebase Storage and HTML using TypeScript without Angular or React in IntelliJ?

My project goal is to create a functional login and register page using TypeScript. Currently, my code operates without a database, but I aim to implement Firebase for registering user credentials for easy login. I have only come across tutorials using F ...

Node JS application facing compatibility issues with Typescript not working as intended

I've been diving into Typescript and recently followed a tutorial on how to integrate it with an express api app. However, I encountered the following error: D:\Development\Node\Ed\TypeScript\src\app.ts:5 const app: Appl ...

Modifying the property value based on the selected item from a dropdown menu in Angular 2

I am brand new to Angular 2 and I have come across the following code snippet. <select name="shape_id" (change)="changeShape()"> <option *ngFor="let shape of shapes" [ngValue]="shape.name"> {{shape.name}} </option> </s ...