What is the best way to determine which variable holds the greatest value in Angular?

I am working with different array lengths stored in variables and trying to determine which variable is the greatest, then change the font color of that variable. However, I encountered an issue where if two variables have the same value, only one is being colored.

Here is my code snippet:

  calculateconfirm(location1, location2, location3, location4, type) {
    var max = Number.NEGATIVE_INFINITY;
    var max_key = undefined;
    var obj = { 'location1': location1, 'location2': location2, 'location3': location3, 'location4': location4 };
    for (var key in obj) {
      if (obj[key] > max) {
        max_key = key;
        max = obj[key];
      }
    }
    return max_key == type ? '#5D3FD3' : '#301934';

  }

HTML

  <tr *ngFor="let x of userdata">
        <td><img src="{{x.data.userImage}}" alt="" style="height: 75px; width: 75px;"></td>

        <td>{{x.data.fullName}}</td>
        <td *ngIf="x.data.location.location1 == 'false'">N/A</td>
        <td *ngIf="x.data.location.location1 != 'false'"
            [style.color]="calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location1')">
            {{x.data.location.location1}}

        <td *ngIf="x.data.location2.location2 == 'false'">N/A</td>
        <td *ngIf="x.data.location2.location2 != 'false'"
            [style.color]="calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location2')">
            {{x.data.location2.location2}}


        <td *ngIf="x.data.location3.location3 == 'false'">N/A</td>
        <td *ngIf="x.data.location3.location3 != 'false'"
            [style.color]="calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location3')">
            {{x.data.location3.location3}}

        <td *ngIf="x.data.location4.location4 == 'false'">N/A</td>
        <td *ngIf="x.data.location4.location4 != 'false'"
            [style.color]="calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location4')">
            {{x.data.location4.location4}}
        </td>

    </tr>

Let's assume we have an object like this:

var obj = { 'location1': 2, 'location2': 1, 'location3': 5, 'location4': 5 };

In this case, I want both location 3 and 5 to be colored on the HTML page.

Answer №1

To effectively manage multiple keys that have the same highest value, it is essential to update and replace existing keys when a new maximum value is discovered. Here is an enhanced version of your current function that handles this scenario:

  adjustValues(location1, location2, location3, location4, type) {
    var max = Number.NEGATIVE_INFINITY;
    // store keys in an array to accommodate multiple keys
    var max_keys = [];
    var obj = { 'location1': location1, 'location2': location2, 'location3': location3, 'location4': location4 };
    for (var key in obj) {
      if (obj[key] > max) {
        max_keys = [key];
        max = obj[key];
      } else if (obj[key] === max) {
        // add key to list in case of tie
        max_keys.push(key)
      }
    }
    // check if type matches any of the keys
    return max_keys.includes(type) ? '#5D3FD3' : '#301934';

  }

Answer №2

To simplify the process, calculate the maximum value only once and then compare it with the known value to assign the style. Here is an example showing this approach:

export class AppComponent  {
  
  items = [
    { name: 'Item #1', value: 3 },
    { name: 'Item #2', value: 2 },
    { name: 'Item #3', value: 3 },
    { name: 'Item #4', value: 5 },
    { name: 'Item #5', value: 4 },
    { name: 'Item #6', value: 5 },
  ];

  maxValue = Math.max(...this.items.map(i => i.value));

}
<li *ngFor="let item of items" [style.color]="item.value === maxValue ? 'red' : 'black'"> 
    {{ item.name }} ({{ item.value}})
</li>

A ternary operation is used to determine the style value by comparing each item's value against the calculated maxValue.

Avoid calling functions directly from the template since they get executed every time Angular's change detection runs. This can impact performance, especially as data sets grow larger or function complexity increases.

Here is a StackBlitz sample for reference.


If you have multiple values in each row of data, you can still use the same method of calculating the max value for each row. You can add a new property named maxValue to each object in the array like so:

export class AppComponent  {
  
  private dataItems = [
    { name: 'Item #1', values: [3, 1, 2, 3] },
    { name: 'Item #2', values: [8, 2, 5, 3] },
    { name: 'Item #3', values: [3, 4, 2, 4] },
    { name: 'Item #4', values: [5, 5, 1, 9] },
    { name: 'Item #5', values: [4, 8, 1, 8] },
    { name: 'Item #6', values: [5, 1, 6, 7] },
  ];

  items = this.dataItems.map(item => ({
    name     : item.name,
    values   : item.values,
    maxValue : Math.max(...item.values)
  }));

}
<tr *ngFor="let item of items">
    <td> {{ item.name }} </td>
    <td *ngFor="let value of item.values" 
        [style.color]="value === item.maxValue ? 'red' : 'black'"
    > 
        {{ value }}
    </td>
</tr>

Refer to StackBlitz #2 for another example.

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

The type 'MutableRefObject<undefined>' cannot be assigned to the type 'LegacyRef<HTMLDivElement> | undefined'

I have created a customized hook that takes a ref object and observes its behavior: import { useState, useEffect, MutableRefObject } from "react"; const UseOnScreen = (ref: MutableRefObject<undefined>) => { const [isIntersecting, setI ...

Is there any distinction between using glob wildcards in the tsconfig.json file when specifying "include" as "src" versus "include" as "src/**/*"?

Is there a distinction between these two entries in the tsconfig.json file? "include": ["src"] "include": ["src/**/*"] Most examples I've come across use the second version, but upon reviewing my repository, ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

Infer the types and flatten arrays within arrays

I am currently working on creating a custom function in typescript that can flatten nested arrays efficiently. My current implementation is as follows: function flattenArrayByKey<T, TProp extends keyof T>(array: T[], prop: TProp): T[TProp] { re ...

Troubleshooting CORS policy problems in an Ionic Angular application

I am attempting to run the following function in my Ionic Angular application, where cloudFunctionUrl represents a cloud function within my Firebase project: import { HttpClient } from '@angular/common/http'; private http: HttpClient like(post) ...

The Typescript SyntaxError occurs when attempting to use an import statement outside of a module, typically within a separate file that contains

I am currently developing a Minecraft bot using the mineflayer library from GitHub. To make my code more organized and reusable, I decided to switch to TypeScript and ensure readability in my project structure (see image here: https://i.stack.imgur.com/znX ...

Angular 5 and Bootstrap card with enhanced double-click functionality

I want to design a Bootstrap card that can trigger two of my custom methods. <div (click)="TEST1()" class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <button (click)="(T ...

Error: The recursive list cannot access the 'length' property of an undefined value

I am experiencing an issue with my recursive list, as I am unable to retrieve the entire list. <ul> <ng-container *ngTemplateOutlet="recursiveListTmpl; context:{ list: famillies }" ></ng-container> </ul> <ng-te ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

The Angular Reactive Forms error message indicates that attempting to assign a 'string' type to an 'AbstractControl' parameter is invalid

While attempting to add a string value to a formArray using material forms, I encountered the following error message: 'Argument of type 'string' is not assignable to parameter of type 'AbstractControl'.' If I try adding a ...

What is the proper way to specify the type for a <video> element reference in React when utilizing Typescript?

I have been experimenting with controlling the play/pause state of a video in React.js using ref's. My code functions correctly but I am encountering tslint errors that I am currently trying to diagnose: function App() { const playVideo = (event:a ...

Issue: "Exported functions in a 'use server' file must be async"

I'm currently working on implementing layout.tsx in the app directory of Next.js 13 to create a navigation layout that appears on all pages. I've successfully configured it so that the navbar updates when a user logs out or signs in, but there&ap ...

Guide on showing a component exclusively for iPads with React and TypeScript

I need help displaying an icon only in the component for iPad devices, and not on other devices. As a beginner in coding for iPads and mobile devices, I am unsure how to achieve this specific requirement for the iPad device. Below is the code snippet tha ...

Enhancing Angular2 authentication with Auth0 for enabling Cross-Origin Resource Sharing

I have been working on implementing user authentication through Auth0. I followed the instructions provided on their website, but I am encountering authentication issues. Whenever I try to authenticate, an error message appears in the console stating that ...

Collection of personalized forms where the parent is a FormGroup

One scenario I'm working on involves creating multiple custom formgroup classes that have FormGroup as their parent class, structured like this: export class CustomFormGroup1 extends FormGroup { //custom properties for this FormGroup const ...

Is it possible to define a data type from an external package using TypeScript and Node.js?

I'm currently in the process of reorganizing some code to utilize a list of signals and connect `.once` handlers to each one individually. const terminationSignals = ["SIGINT", "SIGUSR2", "SIGTERM"]; terminationSignals.f ...

Setting up admin credentials with TypeScript in Firebase cloud functions

While working with Firebase cloud functions in JavaScript, I utilized the following code snippet to initialize admin: admin.initializeApp({ credential: admin.credential.cert(require('./key/firebase-adminsdk.json')), databaseURL: "https://app ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

Exploring Child Types in Typescript and JSX minus the React framework

It seems like there's a missing piece of the puzzle that I can't quite figure out. Despite going through the documentation on JSX in non-React settings, I'm still unable to spot my mistake. Let's examine the following code: /** @jsx pra ...

Angular 6 - The state of the expression was altered after it was verified, different types of constructions

During the build process in debug mode with ng build, I am encountering errors in some components. However, when I switch to production mode using ng build --prod, these errors disappear. I am curious as to why this discrepancy is occurring. Error: Expre ...