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

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

[CSS] What's the trick to getting it to smoothly glide to the top?

As a new designer, I have a question about how to make the background color extend to the top without any white space. Can someone please guide me on how to achieve this? <!DOCTYPE html> <html> <head> <style> body{ margin: 0px; p ...

Activate a tooltip on the button depending on the value entered in the search field

I need to display a tooltip on the button when the search field is empty. Here is what I have attempted: // Enable hover feature const searchBtn = document.querySelector('.find__btn'); searchBtn.addEventListener('mouseover', () => ...

Adjust Fabric js Canvas Size to Fill Entire Screen

Currently, I am working with version 4.3.1 of the Fabric js library and my goal is to adjust the canvas area to fit its parent div #contCanvasLogo. I have tried multiple approaches without success as the canvas continues to resize on its own. Below is the ...

Why am I unable to retrieve the property from the JSON file?

Below is the provided JSON data: data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...

Strategies for enhancing performance in an Angular 4 project

Currently, I am engaged in a project that involves utilizing Angular 4 for the front-end and PHP for the back-end with the support of an Apache server on Ubuntu 16.04 LTS. We have incorporated Node JS to facilitate the functionality of Angular. This raises ...

The chosen Material UI tab stands out with its distinct color compared to the other tabs

Just dipping my toes into the world of Material UI, so bear with me if this question sounds a bit amateur. I've been playing around with Material UI Tabs and successfully tweaked the CSS to fit my needs. Take a look below: https://i.stack.imgur.com/B ...

An error has occurred: Inconsistency found in metadata versions for angular2-flash-messages

I am currently following the Traversy Media MEAN stack front to back playlist on YouTube. However, I encountered an error after importing the flash-messages and I'm having trouble understanding it. I have tried looking at some GitHub issue pages, but ...

Learning the process of interpreting form data in Node.js

I'm currently working with Ionic Angular on the frontend and I am trying to send a formdata that includes a file along with two strings. It seems like the data is being sent successfully, but I am unsure how to access and read this information on the ...

Break down the provided Array type into distinct new types

If we have a specific type defined as: type Tuple = [name: string, age: number, address: string]; and we are interested in creating a new type without the first element, like this: type NewTuple = [age: number, address: string]; Is there a way to achieve ...

What is the CSS method for determining the distance from the top of a container to the edge of the window?

I am working on a basic HTML layout that contains a few elements, including a scrollable div container located below them. Since the height of unknown-height is uncertain due to dynamic element generation, I need a simple method to enable scrolling in the ...

Is there a different approach available since the array function "some" does not restrict type even when a type predicate is implemented?

It is expected that when using the array function "some" along with a type predicate and return statement, the TypeScript compiler would narrow down the type of dashArray. Is it reasonable to expect this behavior from the TypeScript compiler or am I incor ...

Encountering a module not found error when attempting to mock components in Jest unit tests using TypeScript within a Node.js

I'm currently in the process of incorporating Jest unit testing into my TypeScript-written Node.js application. However, I've hit a snag when it comes to mocking certain elements. The specific error I'm encountering can be seen below: https ...

Forward user to a subdomain once they have successfully logged in on an Angular 2 application

I've been working on an Angular 2 application and I'm looking to redirect users from www.example.com to admin.example.com after they successfully log in. What is the best way to accomplish this using Angular 2? Additionally, how can I test this f ...

Leveraging ngIf and ngFor within choice

Is there a way to combine ngIf and ngFor in a single line of code? Here is the code snippet I am currently using: <option *ngIf="tmpLanguage.id!=languages.id" *ngFor="let tmpLanguage of languages" [ngValue]="tmpLanguage.id"> {{tmpLang ...

Switching from a layout of 3 columns to 2 columns on iPad when orientation is changed to portrait

Apologies for posting this inquiry here, but I am facing a challenge with an iPad issue when switching to portrait orientation on my website. I am using a @media query to detect the portrait view and I want to switch from three columns to two. However, th ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

Angular 2 component: Harnessing the power of boolean inputs

I am currently working on creating a reusable component for my application that may display a control button at times and hide it at others. My ideal scenario would involve utilizing the presence or absence of an attribute to determine whether the control ...