Show variously colored information for each selection from the dropdown using Angular Material

I am trying to change the color of displayed content based on user selection in an Angular application. Specifically, when a user chooses an option from a dropdown list, I want the displayed text to reflect their choice by changing colors. For example, if the user selects "Confirmed" from the dropdown, the text should display in green. If they select "Not Confirmed", the text should be red. And if they choose "Confirmed and Shipped", the text should appear yellow. I have been struggling to implement this functionality as I am new to Angular. Any guidance on how to achieve this would be greatly appreciated.

<mat-form-field>
  <mat-select placeholder="Status" [formControl]="statusTypeFilter">
    <mat-option value="1">Confirmed</mat-option>
    <mat-option value="2">Not Confirmed</mat-option>
    <mat-option value="3">Confirmed and Shipped</mat-option>
</mat-form-field>


<div class="table-container mat-elevation-z8">
  <table mat-table [dataSource]="ItemConfirmationList" multiTemplateDataRows matSort matSortActive="no">
    <ng-container matColumnDef="StatusName">
      <th mat-header-cell *matHeaderCellDef mat-sort- header>Status</th>
      <td mat-cell *matCellDef="let element">{{element.StatusName }}</td>
    </ng-container>
</div>

Answer №1

Here are a few steps I took:

  • We saved the selected value from the dropdown in a variable.
  • For each row in our table, we compared the status to this variable and if there was a match, we applied the appropriate class.

Here is the appropriate HTML:

<mat-form-field>
    <mat-label>Status</mat-label>
    <mat-select [(value)]="selected">
        <mat-option *ngFor="let food of foods" [value]="food.value">
            {{food.viewValue}}
        </mat-option>
    </mat-select>
</mat-form-field>
<!-- <p>You selected: {{selected}}</p> -->
<hr/>
    <table>
        <thead>
            <tr>
                <td> Item </td>
                <td> Status </td>
            </tr>
        </thead>
        <tbody>
            <ng-container *ngFor='let pickedItem of sampleItems; let idx = index'>
                <tr [ngClass]="setColor(pickedItem.status, idx)">
                    <td> {{pickedItem.item}}</td>
                    <td>
                        <span *ngIf='pickedItem.status == 1'> Confirmed </span>
            <span *ngIf='pickedItem.status == 2'> Not Confirmed </span>
            <span *ngIf='pickedItem.status == 3'> Confirmed and Shipped </span>
                    </td>
                </tr>
            </ng-container>
        </tbody>
    </table>

Here is the appropriate TypeScript function:

setColor(statusVal, idx){
  let returnedClass:string ='defaultClass';
  (statusVal == this.selected && statusVal ===1) ? returnedClass = 'confirmedClass' : 'defaultClass';
  (statusVal == this.selected && statusVal ===2) ? returnedClass = 'notConfirmedClass' : 'defaultClass';
  (statusVal == this.selected && statusVal ===3) ? returnedClass = 'shippedClass' : 'defaultClass';
  return returnedClass;
}

Here is the appropriate CSS:

.confirmedClass { color:green;}
.notConfirmedClass { color:red;}
.shippedClass { color:orange;}
.defaultClass { color:#000;}

Check out the complete example on StackBlitz

Answer №2

It is recommended to create 3 distinct CSS styles, each tailored for a different status.

CSS Styles

.confirmed {
  color: green;
}
.not-confirmed {
  color: red
}

Subsequently, incorporate the use of [ngClass] in your template to implement the CSS styles accordingly:

<td [ngClass]="{ 'confirmed': status === 'Confirmed', 'not-confirmed': status === 'Not Confirmed', 'confirm-shipped': status === 'Confirmed and Shipped' }"
 mat-cell *matCellDef="let element">
   {{element.StatusName}}
</td>

Note: It is assumed that the value selected from the dropdown menu is stored in the variable status.

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

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Proper Alignment of Div Elements

Just starting out with coding and currently practicing display and positioning. I've created a webpage with multiple divs containing the same content, displayed in a vertical scroll order. Now, I'm looking to position these divs side by side in r ...

Guide to utilizing Angular's translate i18n key as a dynamic parameter within HTML

Looking to pass an i18n translate service key as a parameter function on an HTML component. Attempted the following, but instead of getting the text, it's returning the key value. Created a variable assigned with the title in the component.ts file. ...

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

Positioning an absolute div inside a relative div within a v-for loop while using VueJS and Element UI

I am experimenting with rendering a list of <el-card> items using a transition-group. Each card has a front and back side that flip when a button is clicked. To achieve a smooth flip transition, I need to apply the style: position: absolute; top: 0; ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

Using the ng-app directive value with HTML and CSS can sometimes cause issues and the styles may not apply

angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=mainapp&p1=Error%3A…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.8%2Fangular.min.js%3A19%3A463) <body ng-app=""> It was working fine unt ...

Troubleshooting: Imported Variable in Angular 2+ Throwing Module Not Found Error

During my testing process, I encountered an issue when trying to require a .json file with data to perform checks on. Despite passing the string indicating where to find the file into the require function, it seems to be unsuccessful... Success: const da ...

Navigating through nested JSON Objects for dropdown functionality in Angular 6 - a step-by-step guide

Currently, I am facing a challenge in Angular 6.0 where I am trying to use HttpClient to iterate through JSON data retrieved from a local file within my assets folder. Below is the sample JSON Data: [{ "configKey": [{ "user1": [{ ...

Guide to organizing the sequence of text in HTML and CSS

Seeking guidance on reordering text and adjusting spacing on my website. Below, I have attached an image where I intend to change the sequence of text and modify the spacing accordingly. I aim to switch the order from "Resume About Work" to "Work About Re ...

Completion status of circle loader: 100%

I am currently facing some challenges getting the circle loader to work correctly. Although I can handle basic animations, the code I found on CodePen is a bit more advanced than what I am used to. I am using it as a learning experience to understand how i ...

Calculate the quantity of rows within a specific div container

Looking at the image provided, there are multiple divs inside a main div. I am trying to figure out how many rows the main div contains. For instance, in this particular scenario, there are 5 rows. It is important to mention that the inner div is floated ...

Encountering difficulties when attempting to include Spartacus in an Angular application

I'm having trouble integrating Spartacus into my Angular application Here are the steps I followed: Created an Angular application [ng new xyz --style=scss --routing=false] Added a .npmrc file. Ran: ng add @spartacus/[email protected] Now, I&a ...

Is there a method to enhance the efficiency of generating the code coverage report in VSTS?

What are the possible reasons for the extended duration (>1 min) required to generate the code coverage report when running the associated command in VSTS? Are there any strategies that can be implemented to streamline this process? ...

Change the hover effects on the desktop to be more mobile-friendly

In my desktop version, I have implemented some code that enables hovering over a button to display additional information or text. How can I modify this for mobile so that nothing happens when the button is tapped on? .credit:hover .credit-text, .credit- ...

Guide on transferring an array from a regular HTML page to an Angular web component

I have an Angular web component integrated into a regular HTML page. I am trying to pass an array of data from the HTML page to my web component. <script> window.onload = function() { var myArray = [{value: 'aa', name: 'aaa'}, { ...

Encountering an issue while attempting to load in Angular2 RC4: Error: XHR error (404 Not Found) during loading

I encountered an exception while the application was loading on the browser. Here are the details of the error along with the configuration files: Error Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:5 ...

Creating a personalized toolbar for Quill in your Angular project

Currently, I am developing a web application with Angular and aiming to incorporate Quill into it using the ngx-quill library available at here. One of my challenges involves creating a custom embed blot that displays unmodifiable text blocks fetched from ...

Use CSS3 to hide the <li> elements initially and make them appear when the <li> is clicked on

Click here How can I hide the "subline" line from the list and make it visible when the user clicks on the "sub" line, pushing the other lines down? I'm hoping for a solution that doesn't involve using Js or JQuery. Thank you in advance! ...

Dragging and dropping elements using Angular's CDK into a Material dialog box

I am currently facing a challenge while trying to implement Drag and Drop functionality using Angular cdk. My issue arises when attempting to drag an element into a Dialog, which is nested within the container that holds the cdkDropListGroup. To visually r ...