Is it possible to change the color of an element in Angular when using the ngClass and ngStyle directives with

Hey everyone! I've created a StackBlitz demo for reference, where I used an expansion panel to expand content based on click events. For example, clicking on the All element expands all content, while clicking on the B element expands only 'B' content.

What I'm trying to achieve is to use ngStyle or ngClass in the top loop of {{tab}}. When clicking on the All tag, it should change to green color, and clicking again should toggle it to red color. The same behavior should apply to the B tag as well.

If panel state = false, the tag should be red, and when it's true, it should turn green.

Panel open state:

panelOpenState = false;

Top ngFor loop:

<div style="display: flex;justify-content: space-evenly;">
    <div *ngFor="let tab of getTablist();"> <p  (click)='clickOntab(tab)' [ngStyle]="{'color':panelOpenState === 'true' ? 'green' : 'red' }">{{tab}}</p></div>
</div>

Ts File

panelOpenState = false;
  public tabType: string = "";
    
      clickOntab(tab) {
        if (this.tabType != "" && this.tabType === tab) {
          this.panelOpenState = false;
          this.tabType = "";
        } else {
          this.panelOpenState = true;
          this.tabType = tab;
        }
      }
    
      getTablist() {
        const tabList = this.cricketList.map(list => list.alphabet);
        return ["All"].concat(tabList);
      }
    }

Answer №1

To change the color of each tab individually, you can utilize the ngClass directive as illustrated below:

[ngClass]="(panelOpenState===true)?'greenClass':'redClass'"

Currently, all tabs are linked to a single property panelOpenState, causing them to change colors simultaneously. For separate color states for each tab, ensure that you store the open or closed state of each tab in an array. This way, only the currently open tab will display green while others remain red.

For a live demonstration, check out this demo.

Answer №2

In my opinion, the most effective and easy-to-read solution would be:

<div style="display: flex;justify-content: space-evenly;">
    <div *ngFor="let tab of getTablist();">
        <p (click)='clickOntab(tab)' [class.redClass]="!panelOpenState" [class.greenClass]="panelOpenState">
            {{tab}}
        </p>
    </div>
</div>

Answer №3

View the StackBlitz demo here

A straightforward method for incorporating an array containing tab names

  tabs = ["ALL", "A", "B", "C"];
  panelOpenState = "";

To store the name of the open tab in panelOpenState.

Next, update the template file as shown below:

<div style="display: flex;justify-content: space-evenly;">
    <div *ngFor="let tab of getTabList();">
        <p (click)='clickOnTab(tab)'
            [ngStyle]="{'color':panelOpenState === tab ? 'green' : 'red' }">{{tab}}</p>
    </div>

The ngStyle directive will change the text color to green when the tab matches the panelOpenState value, providing the desired functionality.

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

What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...

Challenge encountered while populating dropdown in Angular reactive form

When using template-driven forms, I was able to populate dropdowns. However, now that I'm using material reactive form, I am unable to do so. My goal is to populate the "country" dropdown and then call an "onstatechange" event later on to populate the ...

implementation of a grid tile in an Angular component

Here's what I am attempting to accomplish: <md-grid-list cols="3"> <product *ngFor="let product of products" [product]="product"></product> </md-grid-list> The product component includes a md-grid-tile. The issue: The ...

Set the central axis of rotation directly in the middle

I have implemented an animation to rotate an element, but the issue is that the text within the div does not rotate from the center, causing it to appear a bit wobbly. Is there a way to ensure that the center point of the rotation is in the middle of the ...

What is the best approach for submitting a form with data through a POST request in an Ionic application?

I am facing an issue while trying to make a POST request in Ionic for submitting a form with an array of data. Surprisingly, it works perfectly fine when I test it on POSTMAN. https://i.sstatic.net/t8sEG.jpg Although I attempted to use this form, it did ...

Ensuring Mapael Functions Properly with Vite: A Guide

While some may question the usefulness of this post, I initially wrote it for my own benefit. However, if it can assist just one other person in a similar predicament, that would bring me great satisfaction. Like many Angular Developers, I too have been ea ...

Adjust the margin of a child div based on the parent's width, with the use of JavaScript

Currently, I am developing a website at and I am interested in replicating the layout of another site. The site I would like to emulate is , which features multiple sections with child divs that have margins around them. In order to achieve this effect o ...

Can you please explain how the repeat() function functions? I would like to understand it better

Currently diving into the world of Javascript, I came across this interesting method to create a 16X16 grid using example.repeat(number) with a numerical value. While I have a general understanding of the code flow, I'm struggling to fully grasp how t ...

Move the Material UI popover to the clicked icon's position

I am looking to create a popover similar to the image linked below. When the icon is clicked, I want the popover to display with the same user interface. https://i.sstatic.net/yvKjF.png Here is the code snippet that I have been using: {showPopOver &&a ...

Issue with Angular2 wysiwyg component failing to submitThe Angular2

I'm currently in the process of familiarizing myself with angular2 by developing a sleek wysiwyg component. However, I seem to have reached an obstacle at this point. Below is the code I've been working on: The form that I am utilizing for testi ...

Is there a way to customize the color of the navbar dropdown that appears when the screen size is shrunk?

The current code I have is producing this result. Visit the website I am looking to modify the color of: the three bars Is there a way to do this? I used the nav element for this. Even though I already have custom CSS for navbar colors, I am unsure ho ...

Angular Apollo client makes generating code from graphql files effortless

After discovering the angular graphql code generator through this source, I decided to implement it in my project for generating graphql types and Query services for angular. The contents of my codegen.yml file are as follows. overwrite: true schema: "ht ...

What is the best way to eliminate the indent on both sides of every blog post?

I'm currently using Tumblr and I want to remove the indentation on either side of each blog post. Ideally, I would like the width of the posts to be 100%. Thank you in advance for any help. The website I am working on can be found at . <!DOCTYPE h ...

Click the button to collapse the dropdown menu - Angular Material

Currently, I have implemented the selectTo dropdown feature in angular material design. Here is the code snippet that I am using: <mat-form-field id="inputClick" appearance="outline" (click)="Valid()"> <mat-label>{{'GENERAL.TITLE' | ...

Hidden Div on Google Maps no longer concealing

Since early December, the Google map on my site has been working perfectly. However, the other night, I noticed that the map now defaults to open when entering the site and cannot be closed. Strangely, all my Google maps are behaving this way even though n ...

Is there a way to incorporate a dropdown feature into a search bar using Ant Design?

I'm currently working on a project that requires me to incorporate two drop-down menus inside the search box. Despite following the guidelines provided in the documentation (https://ant.design/components/input), I encountered a problem when trying to ...

"Achieving Alignment: Placing a Div Element Inside an H

I am in the process of building a portfolio for freecodecamp, but I am having trouble with centering the button and row div on the page. The row div is necessary because I will be adding more buttons later on, but for now I just need the FCC button. Below ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...

Rearrange information when the textarea is adjusted in size

One issue I am facing is that when I resize the textarea in my form, the content below the textarea does not move along with it. How can I ensure that the content moves accordingly when resizing the textarea? <form name="contactform" method="post" ...

Organizing Bootstrap Columns

Currently, I am facing an issue with the footer section of the website I am working on. The problem lies in the order in which the elements are displayed. I would like the social icons to appear above the copyright symbol. Take a look at the footer. Here ...