Efficiently linking styles through computation in Angular

So I've been working with Angular5 and I figured out how to bind an HTML element's style to a Boolean value. However, I'm struggling to find a way to do this for multiple styles simultaneously.

For example, I have this code snippet that works:

[style.background]="r.favourite === true ? '#3f51b5' : 'white'"

But now I also want to change the text color to white when r.favourite === true. I don't want to clutter my components with numerous [style.xxx] tags.

Is there a method to dynamically bind to a CSS class to apply when r.favourite === true?

I know there are ways to achieve this if you're binding within the same file as shown here:

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

@Component({
    selector: 'my-app',
    template: `

    <button class="my-btn" [class.extraclass]="someProperty">Call to Action</button>
`,
    styles: [`
    .my-btn { font-size:1.7em; }
    .extraclass { background: black; color: white; }
    `]
})

export class AppComponent { 

    someProperty = true;

}

However, in my case, the CSS is stored in a shared file so my project structure looks like this:

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

@Component({
    selector: 'my-component',
    styleUrls: ['./css/shared-styles.css']
    template: `

    <button class="my-btn" [class.extraclass]="someProperty">Call to Action</button>
`
})

export class MyComponent { 
    someProperty = true;
}

Answer №1

If you want to style elements dynamically in Angular, consider using NgClass.

<div [ngClass]="{'text-success':r.favourite ,'text-danger':!r.favourite}">

Define the classes 'text-success' and 'text-danger' as needed for your styling requirements. For more information on how to use NgClass and NgStyle effectively, check out this informative article:

This should provide you with some valuable insights.

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

Injecting the environment into a service in an Angular project with multiple modules: A step-by-step guide

In my Angular project, I have developed two separate applications along with two libraries. In order to make use of a service across both apps, I created the service within one of the libraries. However, I am facing an issue because the service requires a ...

Is there a way to remove data from the database if a specific insert statement is unsuccessful?

My website consists of 5 inputs and an html table. The goal is to check the checkboxes in the table by looping through it and fetching the data. Since the inputs and data in the table are interconnected, a failed insert statement can pose a problem. Curre ...

"Wordpress Pluto theme: A stellar choice for your

I'm trying to add a link in my main template.index file that will redirect to one of my pages when clicked on the JavaScript button at the top in Pluto theme. Currently, the text is there but clicking on it opens something I don't want. Here&apo ...

Tips on modifying webpage content based on page size (zoom) in responsive web design using CSS

I have a good understanding of responsive design and how to set elements with relative width. My specific question is regarding the transition of the page from thisto that. Any insight on this would be greatly appreciated. Thank you in advance. ...

Utilizing jQuery to Adjust Tab Transparency

I'm trying to add some opacity to my jQuery tabs, but so far I've only been successful with accordions. Any tips or tricks for achieving this effect with tabs? Styling with CSS .ui-tabs{ background-image: none; background: rgba(204, 204 ...

Customizing Navigation Color on Laravel Websites for Staging and Live Servers

I am seeking a solution to change the color of the Laravel navigation bar depending on whether it is the live or staging server. Our current setup involves testing code on a staging server before pushing it to the live server in production via Bitbucket. ...

The position of the scroll bar remains consistent as you navigate between different websites

Is it possible for me to click on a link within my HTML website and have the other website load with me in the exact same position? For example, if I'm halfway down a webpage and click a link, can I be taken to that same point on the new page? If so, ...

Transfer items on a list by dragging and dropping them onto the navigation label of the target component

I'm currently exploring how to move an element from a list to a <div> and then see it transferred to another list. The objective is to allow users to drag items from one list onto the labels in a sidebar navigation, causing the item to switch t ...

The Google map is not appearing when placed within the "row" class

My goal is to showcase Google Maps on my website, and every time I try to do so using the following code: <div class="large-12 columns" id="map-canvas"></div> The map displays perfectly and works as expected. However, when I nest this div wi ...

CSS selector for detecting elements with empty or whitespace-only content

A special selector called :empty allows us to target elements that are entirely devoid of content: <p></p> However, in some cases, the element may appear empty due to line breaks or white spaces: <p> </p> In Firefox, a workar ...

How can I send an HTML document from a WebApi 2 action using the IHttpActionResult interface?

When it comes to building an html document and returning it in a web api, many resources recommend using HttpResponseMessage. However, I am eager to achieve this using IHttpActionResult instead. Here is my current approach: [ResponseType(typeof(HttpRe ...

From where does the require.js file originate?

Currently, I am learning Angular 2 from the tutorial available at https://github.com/pkaul/maven-typescript-example. Once I proceed with the 3rd step (mvn jetty:run), a runnable war folder is generated in the example-webapp/target directory. However, I ha ...

Currently, my goal is to create a functional copy button through the use of JavaScript

I've been attempting to create a basic copy button using JavaScript, but I keep encountering an error. TypeError: null is not an object (evaluating 'myInp.select') Whenever I click the copy button, My code looks like this: <!DOCTYPE htm ...

Steadfast item securely fastened to its guardian

How can I ensure a fixed object within a relatively positioned parent is clipped to its parent's boundaries as it moves with scrolling down the page? I have been trying to find a solution for this issue, but haven't had any luck so far. ...

Tips for incorporating a dynamic CSS style sheet into a standalone xhtml document

I am faced with the task of incorporating two CSS classes into a single xhtml. For instance: Take, for example, display.xhtml, which will be utilized by two different applications, each requiring its own CSS styling. This means that if display.xhtml is ...

PHP: When MySQL is not returning results and an undefined variable is causing issues

Currently, I am engaged in a project where I need to fetch some data from the database and display it within a form. Although my SQL query seems correct when reviewed in the SQL log, MySQL is not returning any results. I am seeking assistance on how to ret ...

Issues with loading Angular 4 Bootstrap JS post compiling

Utilizing normal bootstrap 3 within an Angular 4 application has been working well when compiling for development using ng serve. However, upon building the application with ng build, I encounter an issue where my bootstrap.js fails to load. Below are th ...

Error message: "The function platform_browser_dynamic_1.bootstrap does not exist in Angular 2."

I had everything set up and running smoothly until suddenly I started receiving this error out of nowhere: TypeError: platform_browser_dynamic_1.bootstrap is not a function Here's the component I've been working on: import { Component, Input, ...

The toggle function for the classList ('open') is functioning correctly and can be seen in the inspect element tool, however, the website is not displaying the associated style

How can I make the .nav show styles in .open after clicking #menu-icon? Note: I used Bootstrap to create the nav HTML <!-- logo --> <div class="logo"> <img src="assets/logo.png" alt="logo g's shop& ...

Learn how to send dynamic data to another HTML element using Ajax's success function

I received a successful ajax response from one HTML file, but I'm struggling to dynamically set the data from this response to another HTML file. Can anyone help me with this issue? Here is the code snippet from my ajax report: success: function( ...