Incorporate dynamic HTML into Angular by adding CSS styling

Just starting out with Angular and have limited front-end experience. I'm feeling a bit lost on how to proceed. Currently, I have a mat-table with a static datasource (will connect to a database in the future), and I need to dynamically change the background color of cells in a specific column based on whether they display "pass" or "fail." Where should I begin with this task? I've grasped the basic logic:

if (result == "pass") { add green styling}
else {add red styling}

But how can I implement this in reality using Angular? Any guidance would be appreciated.

Answer №1

try out this example :

  <div [ngStyle]="{'color': answer === 'correct' ? 'blue' : 'orange' }"></<div>

Answer №2

To achieve this effect, consider utilizing NgStyle as the most suitable method. Below is an example to demonstrate:

<div [ngStyle]="{'background-color': status === 'success' ? 'green' : 'red' }"></<div>

When the status is 'success', the background color of your div will be green; otherwise, it will be red.

For additional insights, feel free to visit this link.

Answer №3

As no reproducible example was provided, let's refer to a sample from the official Angular Material table documentation.

In this scenario, you have the flexibility to apply custom styles to individual cells based on specific conditions:

component.ts

import { Component, VERSION } from '@angular/core';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
}

HTML template

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef>No.</th>
    <td mat-cell *matCellDef="let element">{{ element.position }}</td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>Name</th>
    <td mat-cell *matCellDef="let element">{{ element.name }}</td>
  </ng-container>

  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef>Weight</th>
    <td mat-cell *matCellDef="let element">{{ element.weight }}</td>
  </ng-container>

  <!-- Custom Styling -->
  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef>Symbol</th>
    <td 
      [ngStyle]="{ 
        'background-color: element.symbol === 'pass' ? red : green' 
      }" 
      mat-cell 
      *matCellDef="let element">{{ element.symbol }}
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>

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

Issue with PHP Form data not syncing with MySQL Database

I have been attempting to create a form and upload it into my database, but unfortunately, it is not functioning properly. Here is the HTML code I am using: <form name="Form-Request" method="post" action ="icn/form.php"> <div> ...

"Creating Rounded Corners in HTML: A Step-by-Step Guide

Is there a way to round the corners of this image? Below is an excerpt from my body... <body> <h1 style="float:left; width:37%;"><font color="#99CC00"><font face="Verdana">MrEpicGaming4U</font></h1> <div style= ...

Changing the Image Source in HTML with the Power of Angular2

Despite my efforts, I'm unable to display the updated image in my HTML file. In my TypeScript file, the imageUrl is updating as expected and I've verified this in the console. However, the HTML file is not reflecting these changes. In my researc ...

Having trouble with implementing the .addclass function in a dice roller project

I'm looking to have the element with id=die load initially, and then on a button click event labeled "click me," apply the corresponding CSS class such as 'die1,' 'die2,' and so forth. function roll() { var die = Math.floor(Ma ...

Using @at-root seems to be causing an error when combining the "a" selector with

I encountered an issue when attempting to use @at-root and Interpolation in my Sass code. Despite using a standard example for testing, I still receive an error: .button { @at-root a#{&} { color: green; } } Error sass/Site.scss (Line 28 of s ...

Effortlessly connecting Angular with forms

Check out this jsfiddle demo: https://jsfiddle.net/zpufky7u/1/ All the forms on my site were functioning correctly until suddenly angular started binding them all with class="ng-pristine ng-valid" Could this be due to a setting or something else causing ...

ReactJS incorporates multiple CSS files

I am currently working on developing a Single Page Application using ReactJS. However, I am facing an issue with styling. Currently, I have created 3 different pages (with the intention of adding more in the future), each having its own CSS file that is im ...

Learn how to trigger an event or API call in Angular 8 when the browser is closed with the help of HostListener

I am facing the challenge of calling a simple websocket closure API when the browser is closed in my project. I attempted to utilize HostListener, but unfortunately it did not work as expected. You can find the code snippet below: https://stackblitz.com/ ...

ng-module with tabbed content

I am facing a unique scenario where I have a UserProfileComponent with a tab structure and I want to add tabs from different modules. UserProfileComponent.html <ngb-tabset> <ngb-tab> <app-user-profile-history></app-user-prof ...

Display a div when hovering over a span with custom styling

Don't let the title fool you. http://jsfiddle.net/whb8A/ I'm struggling to style the text inside a span tag within a div. The h3 element shouldn't be nested in the span, but removing it makes it difficult to style with CSS. When hovering ...

Incorporating Angular: A guide to removing a specific element from an HTML array using line breaks

For instance, here is a screenshot of an example: https://i.stack.imgur.com/UlP23.png In the section where I labeled "I want to go down a line", I have an array containing errors related to usernames and passwords. This is how the component.ts file looks ...

Ensure all vertically stacked boxes maintain the same height using Flexbox technology

My design includes a series of links styled as larger boxes, with varying content and height. Using flexbox to ensure equal heights on each row is straightforward. I'm utilizing the Bootstrap grid layout, but when the boxes stack vertically (one per r ...

There is an irritating 5px gap between the divs in the Avada WordPress theme. While using margin-top: -5px helps to reduce this spacing, padding-top: -5

Struggling to remove a persistent 5px whitespace on my website eternalminerals.com See the issue highlighted in this screenshot: Trying to eliminate the whitespace by adjusting margins in Google Chrome, but unable to apply styles to Avada shortcodes: &l ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

"Utilize the attr attribute to showcase an image within an HTML select element

I'm trying to showcase the flag of each country in a dropdown menu. Here is the code I attempted: <select id="slcCountry"> <option flag="https://restcountries.eu/data/afg.svg">AFG</option> <option flag="https://restcountr ...

What should be done in Android when the app crashes due to incoming HTML content?

If I register using an email and password, the process is successful if the email exists within the domain. However, if a malformed email address like [email protected] is used, it returns HTML and crashes my app. How can I handle this issue? publi ...

What is the best way to superimpose an image onto a canvas?

I am working on a cool project where I have created a canvas that displays matrix binary code raining down. However, I would like to enhance it by adding an image overlay on top of the canvas. Here is my current setup: <div class="rain"> ...

A Step-by-Step Guide to Setting Up a Scoreboard for Your Rock Paper Scissors Game

I'm new to JavaScript and I want to create a rock, paper, scissors game from scratch. My Game Plan: Once the user clicks on an option (rock, paper, scissors), the game will display their score and the computer's score along with the result of t ...

How can Node.js and Express be used to conceal Javascript code on the backend?

I'm a beginner when it comes to Node and Express. I have a query regarding how to securely hide Javascript code on the backend. Currently, I am working with Node.js and Express. My goal is to prevent users from easily accessing the code through browse ...

Looking to extract specific information from a webpage using VBA

I'm trying to extract the text 'Catalog Manager/ Sales' & 'EOL (product/component)' from the view source tab using VBA. Here is an excerpt of the view source code: <tr> <td nowrap="true" valign="top" width="165px" cl ...