Disabling Array elements based on a condition in Angular 5

I am managing a list of participants:

<div class="heroWrapper">
    <div class="image hero" *ngFor="let participant of participants; index as i" [class]="i === selectedParticipant ? 'selected hero' : 'image hero'">
        <img [src]="participant.imageUrl" (click)="toggleMoves = !toggleMoves"/>
        <span [ngStyle]="{'color': getColor(participant)}" class="HP">{{participant.hitPoints}}</span>
        <span class="namePlayer" *ngIf="isHero(participant)">{{getPlayerName(participant)}}</span>
        <span class="nameHero">{{participant.name}}</span>
    </div>
</div>

Additionally, there are next and previous buttons available:

next() {
    if (this.selectedParticipant != this.participants.length - 1) {
        ++this.selectedParticipant;
    } else {
        this.selectedParticipant = 0;
    }

    this.toggleMove();
}

previous() {
    if (this.selectedParticipant != 0) {
        --this.selectedParticipant;
    } else {
        this.selectedParticipant = this.participants.length - 1;
    }

    this.toggleMove();
}

The selectedParticipant corresponds to the index of the element in the array. In case a participant's HP reaches 0, I want them to be disabled so that they are skipped by the next and previous methods. Additionally, when disabled, I would like them to appear grayed out.

I attempted to implement the following logic:

if (this.participants[selectedParticipant].hitPoints = 0) {
    ++selectedParticipant;
    if (this.selectedParticipant != this.participants.length - 1) {
        ++this.selectedParticipant;
    } else {
        this.selectedParticipant = 0;
    }
}

This logic needs to be duplicated for each team check. However, it seems to be setting the hitPoints of participants to 0 for some reason?

Answer №1

Make sure to use == in your if statement instead of a single =, as this will prevent setting the hp of participants to 0.

== is used for comparison.

= is used for assignment.

next() {
    if(this.participants[selectedParticipant].hitPoints == 0) {
       ++this.selectedParticipant;
       if (this.selectedParticipant > this.participants.length - 1) {
           this.selectedParticipant = 0;
       }

       this.toggleMove();
    }
}

Answer №2

In this scenario, a mistake has been made by using assignment instead of a comparison.

To prevent this kind of error, it is recommended to always place constants on the left side when writing comparisons in your code.

For example:

if (0 == this.participants[selectedParticipant].hitPoints) { 
}



if (0 = this.participants[selectedParticipant].hitPoints) {
} // This would result in an error during execution because constants cannot be assigned a value, making it easier to identify and fix the issue.

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

Setting up VSCode to run various tasks

My TypeScript project in Visual Studio Code has a specific task outlined as follows: { "version": "0.1.0", // The command is tsc. "command": "tsc", // Show the output window only if unrecognized errors occur. "showOutput": "silent", // Und ...

Updating the user interface in Angular when receiving data via socket.io is currently not feasible

Everything is functioning correctly in my sample application with the web client connecting to the socket.io server. The data being sent by the server over the websocket are being received properly by the client. However, there seems to be an issue when va ...

Angular allows for dynamic sourcing of iframes

I have encountered an issue while trying to integrate a payment system with Angular. The payment gateway API I am using provides the 3D Secure Page as html within a JSON response. My approach is to display this html content within an iframe, however, the h ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Jest's --findRelatedTests fails to identify associated test cases

Whenever I execute the command jest --bail --findRelatedTests src/components/BannerSet/BannerSet.tsx , an unexpected message is displayed: I couldn't locate any tests and hence exiting with code 1 If you want to exit with code 0 even when there are n ...

Is it possible to establish a condition for the component selector in Angular 2/4?

Is there a way to set conditions for a component selector? For example, let's say I have two simple components: First: @Component({ selector:'app-first' templateHtml: 'first.html; }) export class ...

Error message indicating that an object may be undefined in a section of code that cannot possibly be reached by an undefined value

Does anyone have a solution for resolving the Typescript error message "Object is possibly 'undefined'" in a section of code that cannot be reached by an undefined value? This area of code is protected by a type guard implemented in a separate fu ...

Is there a TypeScript equivalent to NSUserDefaults or SharedPreferences?

Just getting started with Angularjs-2.3 TypeScript and I have a specific scenario where I need to save the userId in the app so it can be accessed anywhere within the app. If I were developing for Android or iOS, I would typically use NSUserDefaults and S ...

Unable to bind service data to the kendoUI grid

I'm in the process of developing an angular 4 component incorporating kendoUI. While using the kendoUI grid to display json data, I've encountered a debugging issue. The service seems to be retrieving records successfully, but for some reason, th ...

Angular class change on scroll

HTML <ion-app> <ion-content> <div #scrolledToElement class="second-block" [ngClass]="flag ? 'red' : 'green' "></div> </ion-content> </ion-app> CSS .second-block { margin ...

Is it possible to modify the Angular global error handler to accept additional parameters besides just the error object?

After exploring the capabilities of https://angular.io/api/core/ErrorHandler, I have found that it allows me to override the global error handler with an error object. I appreciate how I can easily define my own global error handler and use it wherever nec ...

refresh specific route when navigating to the same URL

Can the onSameUrlNavigation: reload be applied to just a single route in Angular? ...

transmit data from Node.js Express to Angular application

I am making a request to an OTP API from my Node.js application. The goal is to pass the response from the OTP API to my Angular app. Here is how the API service looks on Angular: sendOtp(params): Observable<any> { return this.apiService.post(&q ...

Creating a personalized NPM package: Converting and exporting TypeScript definitions

Question: Do I need to adjust my TS configuration or add a TS build step? I recently developed a new npm package: Custom-NPM-Package / - src -- index.js -- index.d.ts -- IType.ts accompanied by this tsconfig.json: { "compilerOptions" ...

Refresh the context whenever the state object changes

Within my application, I am utilizing a PageContext to maintain the state of various User objects stored as an array. Each User object includes a ScheduledPost object that undergoes changes when a user adds a new post. My challenge lies in figuring out how ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Guide to making a Typescript type guard for a ReactElement type

I'm currently working with three TypeScript type guards: const verifyTeaserOne = (teaser: Teaser): teaser is TeaserOneType => typeof teaser === 'object' && teaser.type.includes('One'); const validateTeaserTwo = ( ...

List of items:1. The first item is elevated in its position

Can anyone explain why the first li item is displaying higher than the rest when I assign an id or class to the div element? https://i.sstatic.net/9SMdT.png Take a look at the code snippet below: <div id="pickList"> <ul *ngFor="let channel ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...