I am facing a situation where I need to apply identical ngStyle to two different elements. How can I avoid repetition and maintain code efficiency?

I am looking to customize the ngstyle

            <p class="is-discount" [ngStyle]="{
                'background-color':
                  bicycle.discount > 70
                    ? 'red'
                    : bicycle.discount > 60
                    ? 'pink'
                    : bicycle.discount > 50
                    ? 'orange'
                    : null
              }">
              -{{ bicycle.discount }}%
            </p>
          <p [ngStyle]="{
              'color':
                bicycle.discount > 70
                  ? 'red'
                  : bicycle.discount > 60
                  ? 'pink'
                  : bicycle.discount > 50
                  ? 'orange'
                  : null
            }">
              {{
                bicycle.price - (bicycle.discount / 100) * bicycle.price
                  | currency: "EUR"
              }}
            </p>


      

Answer №1

To apply the same styling using ngStyle to both elements, create a variable in your component's .ts file:

myStyle = {
           'color':
            bike.discount > 70
            ? 'red'
            : bike.discount > 60
            ? 'pink'
            : bike.discount > 50
            ? 'orange'
            : null
          }

You can then utilize this variable in your component's .html file like so:

<p class="is-discount" [ngStyle]="myStyle">
  -{{ bike.discount }}%
</p>

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

Enhance Your NextJs Website with Interactive Tooltips using @tippyjs/react

<Link href="/company/add" > <a title="My New Title" data-toggle='tooltip' className="btn btn-primary">My Link</a> </Link> Trying to integrate a Tippy tooltip component with a Nextjs Link do ...

Is it possible to utilize context within a custom hook?

Here is a custom hook that attempts to use context inside it, but results in an error stating "Invalid hook call. Hooks can only be called inside of the body of a function component" export const useFetch = async () => { const { city, setFetchError } = ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

Exploring the wonders of tokeninput with jQuery and JavaScript

After updating the code, the focus is now working. However, I'm facing a problem with getting the phone number that the user entered and placing it in front of the text in the input field called "id="some-text"? <input id="some-text" type="text" ...

Primeng - Displaying names in editable datatable with multiSelect feature

Lately, I have been exploring primeng and I am interested in creating an editable table that includes a multi-select column. After some experimentation, I managed to achieve this result. However, my issue is that I want the winners field (which contains a ...

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

What steps should be taken to refresh a page following an AJAX file upload?

I need some help creating a progress bar to track file uploads on my website. Here's what I have so far: HTML: <form action="upload/files.php" method="post" enctype="multipart/form-data" id="frmUpload"> <input type="file" name="upfile" ...

What is the best way to access a video stored in a local file on the initial page and then watch it on the subsequent

I recently encountered a scenario where I needed to select a video on one page and have it automatically play on another page without any redirection. The initial page displays a list of videos for selection, like this: FirstPage Once a video is chosen on ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Guide to creating a setter for an array property in Angular 2 (Typescript) that will be filled by the view

Question: private _secretQuestions: {question: number, answer: string}[]; Within my HTML, I have three select boxes representing questions, each with a corresponding input box for answers. My goal is to map the selected questions and input values to the ...

Unexpected termination during the npm installation process without providing a clear error message

Every time I try to create a new Angular2 app using the command ng new new-app, angular-cli successfully generates the necessary files and then proceeds to run npm install. However, the npm install process abruptly stops with no error message provided. As ...

Setting up an Angular development environment without relying on the CLI framework

I've been diving into learning Angular and experimenting with demo apps, but I'm finding it difficult to get a clear understanding of how everything works and the underlying concepts. Most resources I come across emphasize using CLI for automatio ...

Incompatible parameter type for the Angular keyvalue pipe: the argument does not match the assigned parameter type

I need to display the keys and values of a map in my HTML file by iterating over it. To achieve this, I utilized Angular's *ngfor with the keyvalue pipe. However, I encountered an error when using ngFor: The argument type Map<string, BarcodeInfo ...

Unable to shake off a sudden burst of information following the ajax page load

I am facing an issue with my page that involves making different ajax calls based on user clicks. There are four IDs, and only one should be visible at a time. However, when new ajax content is loaded into a div, I experience a brief flash of the previou ...

Updating a slider based on the values of two other sliders can be achieved by implementing a

I am working on a project that involves three input sliders. I need the third slider to display the product of the values from the first two sliders. Additionally, I want the value of the third slider to update dynamically whenever the values of the first ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

Creating and implementing a HTML template from scratch, devoid of any frameworks

Is there a way to create a quiz where all questions follow the same format and only one question is displayed at a time, without duplicating code? Perhaps using a template would be the ideal solution in this scenario. I appreciate your help. ...

What is the best way to create a smooth sliding effect using CSS?

Need help with creating a transition effect within a bordered div that reveals hidden content when a button is clicked? I'm looking to have the <a> tag displayed after clicking the button, with both the button and text sliding to the left. Here& ...

Angular Elements: the crucial link to Material Dependencies

Currently in the process of developing an Angular Element for integration into various projects. This element will serve as a component housing Angular Material components within its template, necessitating the inclusion of a linked Material theme CSS file ...

What could be causing the tooltip to appear in the wrong position

It may seem like a trivial issue, but I am struggling to get my tooltips to display in the correct position. No matter what I try, they always appear off position. I have searched for solutions and attempted to rearrange the order of scripts, add new scri ...