Applying ngClass to handle positive and negative numbers and adjust color in Ionic/Capacitor

I have data from my API that includes price and percentage data. I want to display negative numbers in red, and zero or positive numbers in green. After exploring Angular documentation, I found that ngStyle and ngClass can be used for this purpose. I chose ngClass for code reusability across different pages. Here's what I have:

<ion-row>
  <div>{{Prices}}</div> 
</ion-row> 

And

<ion-row>
      <div>{{PricesPercentage}}</div> 
</ion-row> 

The data is as follows:

Price:

1304.53

PricesPercentage:

2.33906, -0.04118

I aim to apply the "red" CSS class to negative values.

.green-color{
 color:green;
}

.red-color{
    color:red;
}

After searching on Google, I attempted two solutions:

Solution 1: using a function

 checkNumberColor(numberCheck) {
    if (this.numberCheck >= 0,0) {
      return 'green-color';
    }
    if (this.numberCheck < 0,0) {
      return 'red-color';
    }   
  }

I then bind it like this:

  <div [ngClass]="checkNumberColor(PricesPercentage)">{{PricesPercentage}}</div> 

Despite testing, it didn't work with no errors shown in Chrome Dev Tools.

Angular 2 ngClass function

Solution 2: condition within ngClass

<div [ngClass]="{'red-color' : (PricesPercentage) < 0.00, 'green-color' : (PricesPercentage) >= 0.00}">{{PricesPercentage}}</div> 

How to use ng-class to achieve positive and negative styling angularJs?

I also utilized this documentation to update ngClass:

https://angular.io/api/common/NgClass

Solution 2 is my preference, but unfortunately, upon opening the app, the colors don't change. Can someone guide me in the right direction?

Answer №1

Your use of the [ngClass] directive needs adjustment. To correctly implement it, follow this syntax:

[ngClass]="PricesPercentage > 0 ? 'green-color' : 'red-color'"

Check out this stackblitz demo I just created to showcase the functionality of [ngClass].

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

Some devices experiencing website update issues while others are successful

My website is functioning properly on my laptop and phone, but not on my school iPad (managed by the district). I have already cleared the cache, but the site does not update. It was working fine earlier, and I need to present it next Monday. Please help a ...

Tips for integrating a vertical menu with button icons and subcategories

Currently working on a project with Twitter Bootstrap and looking to create a specific sidebar setup. My goal is to include subcategories using an accordion and a collapsible menu for mobile devices. I came across a similar implementation at http://jsfiddl ...

Troubleshooting: ReactJS CSS Class Issue

I'm fairly new to working with ReactJS and I've encountered an issue while trying to create a class for a specific form. Below is the code I've written: import React, { Component, PropTypes } from 'react'; import s from './s ...

Issues arising with PhoneGap involving ajax and jsonp

My goal is to make an AJAX call to my remote server, send some parameters, and retrieve content. While this script functions well in a web browser, I'm encountering issues when trying to run it with PhoneGap (specifically testing on Ripple and Chrome) ...

Issue with PHP Upload: Index is undefined

Having Trouble with PHP Upload: Encountered an issue: Undefined index: file in Error on line: $count = count($_FILES['file']['name']); Tried numerous codes to fix this error, but none have worked so far PHP Code: <?php $count ...

Dealing with 'TypeError X is Not a Function' Error in Angular (TypeScript): Occurrences in Certain Scenarios and Absence in Others

Recently, I came across an odd issue in Angular 14 where a type error kept popping up. Although I managed to refactor the code and find a workaround, I'm quite intrigued as to why this issue is happening so that I can prevent it from occurring again i ...

Enlargen div or unordered list according to content exceeding limits

What is the best way to ensure a div expands when it contains a lot of content? Code Example (HTML): <div class="content"> Content goes here <br /> Content goes here <br /> Content goes here <br /> Content goes her ...

The intended 'this' keyword is unfortunately replaced by an incorrect '

Whenever the this keywords are used inside the onScroll function, they seem to represent the wrong context. Inside the function, it refers to the window, which is understandable. I was attempting to use the => arrow notation to maintain the correct refe ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

Experience the advanced NgPrime p-dropdown template with templating, filtering, and a clear icon that collapses when wrapped within a form element

Check out this link for a demo Whenever I enclose the code below in a </form> element, the drop-down menu collapses. <h5>Advanced with Templating, Filtering and Clear Icon</h5> <p-dropdown [options]="countries" [(ngModel)]=& ...

When considering Angular directives, which is more suitable for this scenario: structural or attribute?

In the process of developing an Angular 5 directive, I aim to incorporate various host views (generated from a component) into the viewContainer. However, I find myself at a crossroads as to whether I should opt for an attribute directive or a structural ...

Tips for locking the position of a table header and allowing only the table body to scroll

I have designed a table with tbody consisting of 2 tr elements. One tr is used for hiding/showing data. I am trying to keep the Table header fixed while only scrolling the table body. However, as I am using angular js ng-repeat on the tbody, I am encounte ...

Resize images to perfectly fit dimensions of your choice

After conducting thorough research and experimenting with various jQuery and Javascript solutions, I was unable to find a way to dynamically scale images both horizontally and vertically to a specific size while maintaining their aspect ratio. In my parti ...

Extract the content of a textbox within an iframe located in the parent window

Is it possible to retrieve the value of a text box in an iframe from the parent page upon clicking a button? Below is an example code snippet showcasing the situation: <div> <iframe src="test.html" > <input type=text id="parent_text"> & ...

JavaScript preloader function isn't functioning properly when paired with a button

I'm currently working on developing a preliminary landing page for my game using JavaScript. I have integrated a class that overlays my main content, and added an 'onclick' function named fadeOut() for my button in JavaScript. However, the f ...

What steps should be followed to display an HTML page within an HTML div?

The question I have is a bit misleading, as I'm not looking for guidance on how to open an HTML document in a div. Rather, I am currently facing an issue where I am unable to replace the HTML file that I have already placed in a div. Initially, I pla ...

What is the optimal method for storing extracted JSON data?

One question on my mind is how to effectively store JSON data. I have a JSON file that I parse using JSON Library and now I have the data from the file. However, I want to be able to store this data for future use. I'm seeking advice on the best way ...

Issue with array merging/inserting feature not functioning as expected

Here are two arrays that I have: First Array: "workingHours": [ { "opening": "09:30", "closing": "13:30", "dayName": "sunday" }, { ...

Showcase text in a straight row by utilizing ng-repeat and bootstrap

My goal is to show each word on a new line, similar to how words are displayed in a hangman game. The words should be displayed as blanks. <body ng-init="models = [['H','a','p','p','y'],['X',& ...

Prevent duplicate entries for the same ID in Sqlite database

Currently utilizing an android SQLite database and the resulting data is as follows: id | root_id | parent_id |name ---------------------------------- 613 | null | null | m1 612 | null | null | m4 570 | null | null | m1 635 ...