Is there a way to modify Font Awesome icon and text based on a specific condition?

component.html

<i [title]="CardData.quantity > 1 || _ShippingVariable > 1 ? CannotShip : FreeShipping" 
   [ngClass]="{'fa': true,'fa-youtube': socialMediaLink.socialMediaType === 'YOUTUBE',}">
</i>

ShippingVairable is derived from component.ts

My goal is to have the icon be the CrossFontAwesomeIcon in red if _ShippingVariable=0, and the CheckFontAwesomeIcon in green if _ShippingVariable=1.

If anyone has resources or tutorials on Angular NgClass that could help me understand how to dynamically change CSS based on conditions, please let me know.

Answer №1

Consider using this approach instead of [ngClass]

//  Your way
<i [title]="CardData.quantity > 1 || _ShippingVariable > 1 ? CannotShip : FreeShipping" 
   [ngClass]="{'fa': true,'fa-youtube': socialMediaLink.socialMediaType === 'YOUTUBE',}">
</i>

// My recommendation
<i [title]="CardData.quantity > 1 || _ShippingVariable > 1 ? CannotShip : FreeShipping" 
   [class.fa-youtube]="socialMediaLink.socialMediaType === 'YOUTUBE'"
   class="fa" // It appears you always want this class, so keep it outside of conditions
>
</i>

Answer №2

It's quite straightforward: Check out this demonstration

// Suppose you have 2 boolean flags in your component.ts file
boolFlag1: boolean = true;
boolFlag2: boolean = false;

// In your HTML/CSS, you can define any classes

// You want 'class-1' to always be present, 'class-2' to only appear when boolFlag1 is true, and 'class-3' when boolFlag2 is true

Here's how you can achieve that:

<div 
   class="class-1" // This class will always be applied
  [class.class-2]="boolFlag1" // Class2 will be applied when boolFlag1 is true
  [class.class-3]="boolFlag2" // Class3 will be applied when boolFlag2 is true
>
</div>

// In this example, class-3 will not be applied as I have set boolFlag2 to be false

Answer №3

Dear Srikar Phani Kumar Marti, I have gained a better understanding of [class] and [ngClass] thanks to your guidance. Here is how I implemented it:

 <i 
      [class.text-success]="CardData.quantity > 1 || _ProductQuantity > 1"
      [ngClass]="{'fa': true,'far fa-check-square': CardData.quantity > 1 || 
 _ProductQuantity > 1, 'far fa-times-circle': CardData.quantity < 1 || 
 _ProductQuantity < 1}"
      [class.text-danger]="CardData.quantity < 1 || _ProductQuantity < 1"
      >
      {{CardData.quantity < 1 || _ProductQuantity < 1 ? "Cannot
      Ship" : "Free
      Shipping"}}
      </i>
///// By Srikar

// Please remember you can do this too to keep the HTML clean and neat.

// in component.ts file, create a variable for the classes

conditionalClasses = {
     'fa': true,
     'far fa-check-square': CardData.quantity > 1 || _ProductQuantity > 1, 
     'far fa-times-circle': CardData.quantity < 1 || _ProductQuantity < 1
}

// in HTML file, you can do this too! 
<i 
    [class.text-success]="CardData.quantity > 1 || _ProductQuantity > 1"
    [ngClass]="conditionalClasses"
    [class.text-danger]="CardData.quantity < 1 || _ProductQuantity < 1"
>
    {{
       (CardData.quantity < 1 || _ProductQuantity < 1) 
          ? "Cannot Ship" 
          : "Free Shipping"
    }}
</i>

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

Update Angular2 application's routes dynamically

Currently, I am developing an application that involves dynamically loading modules based on JSON data. I am looking to modify the app's routing depending on the user's permission to view certain modules. Can you provide guidance on how to accomp ...

Exploring Angular 7: A guide to implementing seamless pagination with routing for fetching API data

I am new to Angular and I would like some assistance. https://i.sstatic.net/fjpjz.png I need to modify the Route URL http://my_project/products/page/3 when the page changes. The API server provides data through paging, with URLs structured like http://a ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

Requesting Next Page via Angular GET Method for Paginated API

Having trouble loading data from a paginated REST API using the code below. Any suggestions for a better approach are welcome! component.ts import { Component, OnInit } from '@angular/core'; import {HttpClient} from '@angular/common/http&a ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...

Bootstrap Dropdown Menu

When my website is displayed on a large screen, the dropdown menu appears like this: Dropdown Menu I would like the dropdown to open below my Link menu: However, on a smaller screen, the dropdown looks like this: Dropdown Menu2. How can I resolve this i ...

What is the best way to integrate Angular types (excluding JS) into tsconfig to avoid the need for importing them constantly?

Lately, I've been dedicated to finding a solution for incorporating Angular types directly into my .d.ts files without the need to import them elsewhere. Initially, I attempted to install @types/angular, only to realize it was meant for AngularJS, whi ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

Changing field visibility in Angular Reactive form (form validation) by toggling based on a checkbox in another component

I'm facing a challenge with a complex form where the fields depend on toggling checkboxes in a separate component (parent). My goal is to dynamically validate the form, with some fields being enabled and others disabled based on the toggling of the ch ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Tips for efficiently using the debounce feature of valueChanges in reactive forms to prevent entering a patching loop while saving for the first time

Currently, I am working on implementing a debounce feature for my form fields. The challenge arises when dealing with a fresh form that lacks an ID. Upon creating and retrieving the record from the database, it becomes necessary to update the form with the ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

Update not reflecting in Angular Reactive Form custom component value

I've developed a custom input component that extends the primeng spinner component. However, I'm facing an issue with Angular Reactive Form where the model value of my component is not being updated. To make it easier to debug, I've created ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

Having trouble linking tables to Node.js with TypeScriptyntax?

I am facing an issue with mapping multiple entities using sequelize. I keep encountering the error message " Error: Profesor.hasOne called with something that's not a subclass of Sequelize.Model". How can I resolve this issue? Below is the code for t ...

Having trouble triggering the button with querySelector in Angular

I have a dynamic page where I need to click on a button. I tried the code below, but it is not working and not showing any alert. However, if we use the same code in the browser console, it executes and shows an alert. Can someone please suggest how to r ...

How exactly does the 'this' type in TypeScript determine its own type inferences?

When working with TypeScript, I wanted to use the this keyword to type certain properties of my class. However, I encountered a problem that I couldn't figure out how to solve. What I was trying to achieve is something like this: export class Animal{ ...

Setting a filter using mat-auto-select in an Angular template-driven form can be achieved by following these steps

How can I implement a filter with mat auto-select in an Angular template-driven form? <mat-form-field class="pl"> <input matInput name="item_id" [(ngModel)]="stock.item_id" #item_id="ngModel" placeholder="Item" [ ...

Changing the text color of mat-chips in Angular Material

Having a mat-chip-set and multiple mat-chip elements with a custom product-chip class: <mat-chip-set> <mat-chip class="product-chip" *ngFor="let category of categories"> {{category}} </mat-chip> </mat-chip-s ...