Can TypeScript be imported into HTML to set a color value or modify a color value from HTML using TypeScript?

I've been working on this code for a couple of days now. Utilizing Angular to develop a web application, I am trying to change the color of certain numbers when they reach a specific value. For example, if num > 45 then color = green, otherwise color = red. I want to pass the color value between my TypeScript and HTML files, but I'm encountering difficulties with that. The color value passes to HTML correctly, but I'm unable to style it in any way. Here's my code. Appreciate any assistance!

Typescript:

colorOption=''

if(this.Classyaverage > 45){
  console.log('red')
  this.colorOption='#FF0000'
}
else{
  console.log('green')
  this.colorOption='#00FF00'
}

HTML:

<body>
    <div class="pagecolor">

    <div class="box">

      <canvas class="offset"
      id="lineChart" 
      width="240"
      height="180" 
      >
      </canvas>

      //This is what I want...

      <style>
       h1{ color:{{colorOption}};}
      </style>

      <h1>
        {{Classyaverage}}
      </h1>

    </div>

  </div>
</body>

If importing a TypeScript file like this isn't feasible, is there a way to export HTML or CSS into TypeScript?

Answer №1

Define a CSS class to set the color:

.myColor {
    color: var(--colorVariable);
}

Set the value of the CSS variable from TypeScript based on your requirements like this:

document.documentElement.style.setProperty( '--colorVariable', '#00FF00' );

This can be adjusted using calculations or events within the application.

Answer №3

If you're searching for the solution, I believe the ngClass directive is what you need. You can find the detailed documentation about it on Angular's official website.

// .css

.red{
  color: #f00;
} 

.green: {
 color: #0f0
}

-

// .html

<h1 [ngClass]="{'red': Classyaverage > 45, 'green': Classyaverage <= 45}"></h1>

Answer №4

If you find yourself in need of styling multiple elements, there is a way to achieve that easily.

Here's an example:

<h1 class="color-change">
  {{Classyaverage}}
</h1>
<h2 class="color-change" *ngFor"let el of arr">
  test
</h2>

To handle this in TypeScript:

@ViewChildren(".color-change") private colorChange: QueryList<ElementRef>;
constructor(private renderer: Renderer2) { }
ngAfterViewInit(): void {
  this.colorChange.subscribe(() => 
    this.colorChange.forEach((element: ElementRef) => {
      this.renderer.setStyle(
        element.nativeElement,
        'color',
        this.colorOption
      })
    })
  );
}
...

This method works well for both numerous and asynchronous elements.

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

Is placing JavaScript on the lowest layer the best approach?

I'm facing a unique situation that I haven't encountered before and am unsure of how to address it. My website has a fixed top header and footer. On the left side, there is a Google Adsense ad in JavaScript. When scrolling down, the top header s ...

I'm having trouble getting my paragraph to center with both Bootstrap 4's margin:auto and text

I've been trying to center a paragraph in my project but it's not working out. I attempted using margin:0px auto; and the text-center features, but they didn't have the desired effect. <div class="row text-center"> <p> You c ...

Ways to prevent the selection of images

Whenever I click on the ball, a click event is triggered. However, sometimes it doesn't work because I accidentally select the image and it interrupts the click event. I attempted to remove the selectable property using the following CSS properties, ...

Iterate through the complex array of nested objects and modify the values according to specified conditions

I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array. Issue: Th ...

How can I replace the unsightly "Web page not available" error in WebView on Android with a more visually pleasing alternative?

In my WebView Activity, I sometimes encounter issues with loading properly when the WIFI/DATA connection is poor or disconnected. This could potentially be a common occurrence once my app is in use. I'm curious to know how I can replace the unattracti ...

Preserving quotation marks when utilizing JSON parsing

Whenever I try to search for an answer to this question, I am unable to find any relevant results. So please excuse me if this has been asked before in a different way. I want to preserve all quotation marks in my JSON when converting from a string. In m ...

I prefer showcasing the contents at the top of the page instead of the bottom

Is there a way to show the message for the $myGame variable after submitting a post? <!DOCTYPE HTML> <html> <head> </head> <body> <?php $myGame = ""; if ($_SERVER["REQUEST_METHOD"] ...

Troubleshooting a 400 Bad Request Error when calling ValidateClientAuthentication in ASP.NET WebApi, even after using context.Validated()

I am currently facing an issue with my angularjs HTML client connected to a WebApi project. The APIs work fine when tested using POSTMAN or other REST clients. However, when I try to use browsers with my angularjs client, the browsers always initiate prefl ...

Utilizing Custom Script Tag Types in Visual Studio for Enhanced HTML Template Functionality and Improved Syntax Highlighting

Currently, I am utilizing Visual Studio 2012 for editing HTML and JavaScript. My approach involves inserting templates using partial views in inline script tags (view code below). The use of AngularJS, a Javascript framework, dictates that the type must be ...

I encountered a mistake: error TS2554 - I was expecting 1 argument, but none was given. Additionally, I received another error stating that an argument for 'params' was not provided

customer-list.component.ts To load customers, the onLoadCustomers() function in this component calls the getCustomers() method from the customer service. customer.servise.ts The getCustomers() method in the customer service makes a POST request to the A ...

What is the best way to execute a method in a component for each iteration in an *ngFor loop in Angular 2

Is there a way to call a method for each iteration of *ngFor and pass the iterated variable as a parameter? For example: <li *ngFor="let element of componentModel | keys">{{element.key}}--{{element.value}}</li> Then, in the component, I have ...

Sorting an object array by date is causing a problem

UPDATE: Finally cracked the code on this issue. I initially assumed that Date was interpreting the date ("29-04-2020") as DD-MM-YYYY, when it should actually be MM-DD-YYYY. For instance, here's an object array I'm working with: let t ...

Tips on causing JavaScript execution to halt until an element has finished rendering

test.view.js timeDBox = new sap.ui.commons.DropdownBox({layoutData: new sap.ui.layout.GridData({linebreak: true}), change: function(oEvent){ oController.getKeyEqChart(); }, }), new sap ...

Unable to apply inset box-shadow to image

I've added a box-shadow to my image. box-shadow: 0 0 10px RED inset However, the shadow is not showing up on the image. When I use Firebug to change the image path, I can see that the shadow is behind the image. How can I apply the shadow directly ...

typescript set parameter conditionally within a function

For my upcoming app, I am working on an API that will utilize Firebase FCM Admin to send messages. Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import { getMessaging } from "firebase-admin/messaging ...

Displaying a value in a React component using material-ui's TextField

Can anyone help me with printing the email a user enters into the textfield within the Dialog when a button is clicked? I have been struggling to achieve this due to my function's structure. Any guidance would be greatly appreciated. export default fu ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

Having trouble setting up Typescript in VisualStudio 2015 due to the error message "exports is not defined"? Need guidance on the correct setup?

I am new to TypeScript and I am currently learning about exports and imports in TypeScript However, as I started working on it, I encountered an error with exports Object.defineProperty(exports, "__esModule", { value: true }); The error message I receiv ...

Is it considered the most appropriate method to implement a dynamic web page refresh by utilizing PHP, HTML, and AJAX in order to read a

My PHP page currently displays data from a database in tables, but the information is frequently changing. This means that the entire page has to be reloaded every few seconds. I am looking for a way to query the database and update only the section of HT ...

Using Python to extract the title of a hyperlink from an HTML website

<a class="inst" href="http://www.tsetmc.com/loader.aspx?ParTree=151311&amp;i=9987529074833218" target="9987529074833218">كشت و صنعت آبشيرين</a> I am trying to extract the name of the link ("كشت و صنعت آبشيرين" ...