Determine the class for a div within *ngFor by evaluating a condition

I am facing an issue where I need to dynamically assign a class to a div element within a *ngFor loop based on a method. Below is the code snippet from my HTML file:

<ng-container *ngFor="let data of totalData let j = index">
          <div>
            <a (click)="selectData(data)">
              <div [ngClass]="{selected : selectedCodeMethod(data)}">
                {{data.code}}
              </div>
            </a>
          </div>
        </ng-container>

Furthermore, here is the TypeScript code I am using:

selectedCodeMethod(data){
   if(this.selectedCode.includes(data.code)){
             return true;
     }
             return false;
}

selectData(data){
    this.selectedCode.push(data.code);
}

The problem I am facing is that even when the selectedCode array is updated by the selectedCodeMethod() function, the changes are not reflected in the ngClass directive. Can someone please suggest what changes I need to make to fix this issue?

Answer №1

It is not recommended to call functions in Angular templates as it can be inefficient and lead to errors - learn more about this in the linked article.

Instead of calling a function directly, you should create an Angular Pipe that suits your requirements. For example, you can create a pipe named "includes" that takes an array and an element and checks if the element is included in the array:

@Pipe({
  name: "includes"
})
export class IncludesPipe implements PipeTransform {
  transform<T>(array: T[], element: T): boolean {
    return array.includes(element);
  }
}

To use this pipe in your component, you need to pass additional arguments:

@Component({
   selector: "app-root",
   template: `
     <ul>
       <li
         *ngFor="let item of items"
         [ngClass]="{ selected: selectedItems | includes: item }"
       >
         Item {{ item }}
       </li>
     </ul>
   `,
  styleUrls: ["./app.component.css"]
 })
 export class AppComponent {
   items = [1, 2, 3, 4, 5];
   selectedItems = [1, 3];
 }

Remember that pipes are pure, so ensure that you make immutable updates when working with them:

selectData(data){
    this.selectedCode = [ ...this.selectedCode, data.code ];
}

If you want to experiment with the code, you can do so in this Code Sandbox

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

Currently in the process of configuring an ionic project, encountering a series of errors upon executing the npm install command

gyp ERR! configure error gyp ERR! stack Error: Unable to locate Python executable "python", please set the PYTHON environment variable. gyp ERR! stack at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_ ...

Utilizing Spring Boot, Message Queues, Node.js, and Angular to build a scalable microservices

Hello everyone! I recently received a challenging exercise that has left me feeling a bit lost. I was hoping someone could offer me some guidance to get started in the right direction! :) You can find the description of the exercise here (unable to embed ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Utilizing TypeScript with dc.js for enhanced data visualization capabilities

I've encountered an issue with types while working with dc.js version 4.2.7. To address this, I went ahead and installed what I believe to be the standard types module for dc.js using the following command: Command I used for Installation npm i @type ...

Initiating the process of loading a texture atlas using PIXI Js and parcel bundler

I've recently started working with JS programming and pixi JS. I'm attempting to load a texture atlas from a json file following this tutorial module: https://github.com/kittykatattack/learningPixi#spriteproperties For my setup, I am using types ...

The type 'string' is not a valid index for the type 'Partial<NewData>'

Can someone help me resolve this issue? https://i.sstatic.net/GkFYf.png I am looking to encase each object field from the getters argument in a ComputedRef wrapper import { computed, ComputedRef } from "vue"; function useComputedGroup<T exte ...

The array does not yield any values when utilizing Angular CLI

Recently, I created a component that contains an array of strings. Here's the code snippet for reference: import {Component} from '@angular/core'; @Component({ selector: 'app-products-list', templateUrl: './products-list. ...

The deployment on Heroku is encountering issues due to TypeScript errors related to the MUI package

As someone relatively new to TypeScript and inexperienced in managing deployments in a production setting, I've been working on a project based on this repository: https://github.com/suren-atoyan/react-pwa?ref=reactjsexample.com. Using this repo has a ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

In Angular 2, the property is kept private and can only be accessed from within the class

I am currently attempting to compile an Angular 2 application using AOT. Within my project, I am utilizing angular-2-json-schema-form which is leading to errors such as: Property is private and only accessible within class while trying to compile my ap ...

Asynchronous problem when using Firebase calls within an Angular ForEach loop

Here's the code snippet I'm working with: getTotalBookListCost(bookList:string[]):number { let cost=0; bookList.forEach(el=>{ this.store.doc("Books/"+el).get().subscribe(data=>{ let temp=<Book>data.da ...

Is there a way to interrupt the routerLink function when a user is prompted in Angular 4+?

I am seeking to replicate the traditional functionality found in HTML where clicking a link triggers a confirmation pop-up before being redirected: <a href='http://www.example.com' onclick="if ( window.confirm ('Are you sure you want to ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

Unable to run Angular 6 on Windows 10

I'm encountering an issue while trying to run an Angular 6 project on a Windows 10 PC. The Angular CLI is installed with version 11.2.18 and the ng command functions properly. However, when I attempt to execute ng serve, an error related to an RxJs op ...

Discovering the category for ethereum, provider, and contract

My current interface looks like this: interface IWeb3 { ethereum?: MetaMaskInpageProvider; provider?: any; contract?: any; }; I was able to locate the type for ethereum using import { MetaMaskInpageProvider } from "@metamask/providers", ...

What is the best way to access the state value from Redux when the component is opened in a separate browser tab?

Currently, I am in the process of implementing Redux Toolkit into my application. I have successfully created the store and set the value to the state. However, I am facing an issue where I cannot access the value stored in the Redux state when I open the ...

The filename is distinct from the file already included solely by the difference in capitalization. Material UI

I have recently set up a Typescript React project and incorporated Material UI packages. However, I encountered an error in VS Code when trying to import these packages - although the application still functions properly. The error message reads: File na ...

SecurityClient is encountering a problem where the Http Error status is not being displayed

Currently, I am utilizing a custom Http client that is an extension of Angular 4's Http Client. export class SecurityClient extends Http { // ... } Within this client, there are methods designed to make calls to an API and handle a 401 status code by ...

The synergy between ternary operators and Vue filters

Recently, I came across a peculiar issue while working with Vue. Take a look at the code snippet from vue.html: <label :text= "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`"> </lab ...

In TypeScript, a numerical value can be returned as a string when

After creating a numericQuantity variable that is a casted string quantity, I was puzzled as to why the typeof returns string even though the variable is supposed to be of type :number. let quantity: string = '10'; let numericQuantity: number = q ...