NgClass: checking if the array includes the specific item

I'm attempting to apply a class if an item exists within the array, but I'm struggling with it.

  <div *ngFor="let item of someList">

     <button [ngClass]="{'isSelected': selectedArr includes item}"></button>
    ..

selectedArr holds the array that includes certain items.

Answer №1

chosenArray.contains(element) is a viable option. Take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Keep in mind that if element is an object, chosenArray must contain the exact same object, not just an object with identical properties. Otherwise, you will need to devise an alternative approach to compare the object properties for a match. Nevertheless, any valid JavaScript statement can serve as the value for isChosen.

<button [ngClass]="{'isChosen': chosenArray.contains(element)}"></button>

Answer №2

Another approach is to utilize [class.className].

<div [class.isActive]="activeItems.includes(item)"></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

Seeking a solitary undeniably corroborated statement from witnesses

I have implemented a messageBox functionality using p-toast. When a user clicks on delete, they are prompted with a yes or no option before hitting the API to delete the item. The issue I am facing is that if I click on the delete button for one item, sele ...

watcher using RxJS

After recently diving into the Observable and Observer pattern, I came across various resources that describe Observable as a producer and Observer as a consumer. However, as I analyzed the code snippet below, I found myself puzzled by the role of the obse ...

Getting an undefined value for a dynamic directive attribute in Angular5

I am utilizing "@angular/core": "^5.0.1", "@angular/material": "^5.0.0-rc.1", "@angular/cdk": "^5.0.0-rc.1". In my code, I am checking for the presence of a XXXqaName attribute in all fields, so I created a directive with an @input attribute that accepts ...

Mastering the Type Model on Firestore Function to Retrieve Field ValuesUnlock the potential of the Type

When retrieving data from Firestore, I am able to print the entire object using doc.data. However, I am having trouble accessing the specific value of unixtime as it is coming through as undefined. I need help in correctly applying my type model so that I ...

Can someone assist me in configuring the mobile display for an Angular website?

I'm currently working on a website and I'm in need of some assistance to fix the mobile view. The main issue I'm facing is with the menu which contains 5 buttons. While I'm happy with how it looks on a laptop or desktop, the mobile view ...

Is it possible to create a ASP.NET 5 (Core) Website using TypeScript and Node (or ESM) modules within Visual Studio 2019, excluding Visual Studio Code?

After following a helpful guide on setting up TypeScript in an ASP.NET 5 website project using Razor Pages, I decided to enhance my typings with Node modules instead of just importing as 'any'. My goal was to integrate a Node module like EthersJ ...

Dragging element position updated

After implementing a ngFor loop in my component to render multiple CdkDrag elements from an array, I encountered the issue of their positions updating when deleting one element and splicing the array. Is there a way to prevent this unwanted position update ...

Issues arise in TypeScript 5.1.3 with lodash due to type errors involving excessively deep type instantiation, which may potentially be infinite

Recently, I made updates to my Ionic/Angular project and now it is running Angular version 16.1.3 along with TypeScript version 5.1.3. In addition to this, my project also includes the following dependencies: "lodash-es": "^4.17.21", ...

Angular application in a subdirectory experiencing a looped redirection issue

I am currently in the process of setting up an Angular application to be hosted from a subdirectory of an existing website. The main website is located at https://localhost/abc, while the Angular app is being served at http://localhost:4200 using ng serve. ...

Update the data and paginator status

In my development project, I have implemented PrimeNG Turbotable with the code <p-table #dt. Based on information from here, using dt.reset() will clear the sort, filter, and paginator settings. However, I am looking for a solution to only reset the pa ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Tips for customizing labels for boolean filters in DevExtreme data grid

We are looking to change the filter options in the status field (last row) from true/false to Active/Inactive. While there is a coding method to achieve this, we are struggling as we are using a table template. It seems like it should be a simple task but ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Can Angular automatically find files for typescript imports?

I've been working with Angular and using TypeScript. When importing a file in Angular, the syntax usually looks something like this: import { MyService } from '../../../folder/child-folder/my-service.service'; As I progress with my project, ...

Troubleshooting Selenium automation issues with Angular checkbox filter functionality

Developed front-end with Angular 16. I have implemented a checkbox dropdown for filtering, but it requires clicking somewhere on the page to apply the filter. Using Selenium Java automation framework, I can locate web elements and confirm that the checkbox ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Having trouble sending JSON data to API with Angular2's http.post function

After spending nearly a full day on this, I'm still struggling to find a solution. The issue lies with a basic http.post request: import { Component } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@ ...

Generating Enums from JSON REST API in Angular 8

Is there a way to create an enum from a JSON REST API? Here is the code I currently have in my service.ts file: getDataFromJson(): Observable<any> { return this.httpClient.get<any>(`../../../assets/gender.json`) .pipe(map(data => ...

Is there a way to send map data using props in React?

I just want to store and pass the current props.url to the videomodal so I can show the same active video on the video modal. I can't use useState in the map. How can I pass it? Or is there any other solution? Videos.tsx ( props.url must be in the &l ...

How can I select just one element to be impacted by a click event when using map in TypeScript?

Currently, I'm facing an issue where I want to change the icon of a button when it's selected. The problem is that using map affects all buttons even if only one is selected. // ... const [clicked, setClicked] = useState(false); <Button sta ...