What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below:

<ng-container *ngFor="let event of day.availableEvents">
    {{ event.name }}
    <br>
    <ng-container *ngFor="let maleAgeGroup of event.maleAgeGroups">
      <span [class.is-active]="status" (click)="updateStatus()" {{ maleAgeGroup }}</span>
    </ng-container>
</ng-container>

This is the JSON dataset that I'm handling:

"days": [
  {
    "date": "2021-04-14T00:00:00.000Z",
    "availableEvents": [
      {
        "id": 1,
        "name": "Event A",
        "femaleAgeGroups": ["U13", "U15", "U17"],
        "maleAgeGroups": ["U13", "U15", "U17"]
      },
      {
        "id": 2,
        "name": "Event B",
        "femaleAgeGroups": ["U13", "U15", "U17"],
        "maleAgeGroups": ["U13", "U15", "U17"]
      },
    ]
  }
]

Whenever an age group is clicked, my goal is to toggle its status between true and false so that the is-active CSS class can be added or removed accordingly.

Despite trying multiple solutions from Stack Overflow, I haven't been able to make it work properly and often encounter errors like 'Cannot assign status to type string'. Perhaps the issue lies in the structure of my data?

The desired outcome is shown in the example below, where the highlighted text has been clicked and the is-active class is applied:

https://i.sstatic.net/5g1oS.png

Answer №1

[class.is-active] should be linked to a specific value in order to achieve the desired outcome. It appears that each age group should have its own state. Therefore, it is necessary to either update or modify the data from the server, or include the status for each age group within your component...

"femaleAgeGroups": [{name:"U13", active:true}, {name:"U15", active:false}, {name:"U17", active:false}], etc..

Within the template, you can then connect the CSS class to the boolean value as follows:

 <ng-container *ngFor="let maleAgeGroup of event.maleAgeGroups">
      <span [class.is-active]="maleAgeGroup.active" (click)="updateStatus(maleAgeGroup)" {{ maleAgeGroup.name }}</span>
    </ng-container>

To perform updates, pass the item to the update function and toggle its active state:

updateStatus(item:any): void {
   item.active = !item.active;
}
 

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

Dynamic Filtering with jQuery List

I'm attempting to create a dynamic filter list on keypress event. For example, if I type "It" into the input field, the elements that do not match this value will be hidden. I'm unsure if the code structure I have implemented below effectively ac ...

Protected Node.js API paths

Recently, I was developing a login with OTP feature for my app. The front-end is being built using Angular and the back-end on ExpressJs. However, I have been struggling to find a way to secure the API. Every time I test the API using Postman, it works per ...

Unraveling TypeScript code expressions

I am seeking clarification on the meaning and practical application of this particular expression. ((identifier:string) => myFunction(identifier))('Hi') myFunction const myFunction = (str:string) => { console.log(str) } The output displ ...

What steps do I need to take to retrieve the passed slug in my API (slug=${params.slug})?

Is there a way for me to retrieve the passed slug in my API (slug=${params.slug}) while using the vercel AI SDK? const { messages, input, handleInputChange, handleSubmit, isLoading, error } = useChat({ api: `/api/conversation?slug=${params.slug ...

Refining a JQuery scroll animation using mouseover functionality

I came across a JQuery scroll animation (inspired by this specific answer to a similar question that almost perfectly suited my requirements), and I managed to get it working. My goal is to achieve a side-scroll effect of icons when the user hovers over th ...

Establish the default landing page as the home screen when launching the application

Hey, I'm running into a situation where I need to change the default page of my application upon loading. Is there a way to redirect from the home page to another page when the application loads? Thanks! ...

When the click event is triggered, the second function guess() does not execute

I am currently developing a number guessing application. It consists of two functions, the first one called startGame() works correctly (it receives the maximum number and then disappears by adding the hidden class). However, the second function that is ...

Set a string data type as the output stream in C++

I have a method called prettyPrintRaw that seems to format the output in a visually appealing manner. However, I am having trouble understanding what this specific code does and what kind of data it returns. How can I assign the return value of this code t ...

Sharing content on an Angular 4/5 webpage

I find myself in a situation where I am required to share a link to my web application with a client, and they will be submitting a form on my webpage. This application has been developed using Angular 5. Despite searching online for a solution, I have not ...

After receiving the go-ahead from JavaScript, I am planning on integrating PHP into my project. I have come across some recommendations

Looking for assistance with AJAX functionality on a website. Specifically, users should be prompted to confirm a purchase before completing it. If they confirm, the purchase goes through; if they decline, it does not. Originally considered using PHP within ...

Can we create an alias for the import path in TypeScript?

import A = require('../../distant/PathToA'); import B = require('./different/path/PathToB'); I am utilizing external modules (commonJS) and browserify, with WebStorm as my editor. If this were just regular javascript, there are severa ...

Cannot Properly Import JSX Elements in TailwindCSS and React

I am facing an issue with importing a JSX Element into my main file, App.js. The element I want to load is in a separate file called element.js and contains the following code: const element = () => { return ( <div className="text-gr ...

Setting ng-click on a custom element directive in Angular 1.x: A guide

Within this code, I have assigned ng-click to a custom element directive with the expectation that clicking the rendered text would trigger an alert saying "Worked from directive!" However, the functionality does not seem to be working as intended. Althou ...

Store the checkbox's data in the database for safekeeping

Hey there, I'm working on saving the value of a checkbox using PHP. The twist is that the value is generated through JavaScript. How can I handle this scenario and save the value using PHP? Checkbox: <input type='checkbox' name='ca ...

Due to a glitch in the firebase cloud function, the payment is not going through

I have developed a react-redux application with Firestore as the database and now I want to integrate Firebase Cloud Functions to handle Stripe payments. Here is how it's set up: Below is the action method for checkout, which processes token and amo ...

What methods can I use to minimize the duration of invoking the location.reload() function?

When I'm using window.location.reload() in my onClick() function, it's taking too long to reload. I tried modifying the reload call to window.location.reload(true) to prevent caching, but it's still slow. The issue seems to be with location. ...

Creating a dynamic select input in React that displays a default value based on other user inputs

My dilemma involves working with two radio buttons, named radio1 and radio2, along with a select input. The options available in the select input are conditional based on the selected radio button. I am aiming to automatically set the value of the select t ...

The constant value being brought in from an internal npm package cannot be determined

I have developed an internal npm package containing shared types and constants. My project is built using TypeScript with "target": "ESNext" and "module": "NodeNext". Within one of my files, I define: export type Su ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...

Discover choices based on the values in an array

I'm having trouble finding an option in a select menu based on an array value. var array = ["task1", "task2"] var select = document.getElementsByTagName('select'); for (i = 0; i < 2; i++) { $(select).find('option[value=array[i]] ...