Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet:

public defaultStyles = {
    firstDesignBackgroundColor: '#a31329',
    firstDesignFontColor: '#ffffff',
    secondDesignBackgroundColor: '#d1cfcfff',
    secondDesignFontColor: '#000000'
  };

Currently, I want to update my style.scss file with the following statement:

:host ::ng-deep th span#optimize-checkbox-header .mat-checkbox label.mat-checkbox-layout .mat-checkbox-inner-container.mat-checkbox-inner-container-no-side-margin .mat-checkbox-frame {
  border: 2px solid #fff !important;
}

The task is to replace the color value #fff with the variable firstDesignFontColor from the change-service. Is it feasible to create this dependency? Any suggestions or solutions would be appreciated.

Answer №1

If you're looking for a way to achieve this using CSS variables, I have a solution that I will share in another response.

By utilizing JavaScript, it is possible to modify CSS variables. For instance, consider the following example:

:root {
  --bg-color: red;
}

.test {
  background-color: var(--bg-color);
}

You can implement this functionality within your ChangeColorService:

interface Colors {
  background: string;
}

@Injectable()
export class ChangeColorService {
    colors$ = new BehaviorSubject<Colors>({ background: 'red' });

    constructor(@Inject(DOCUMENT) private document: Document) { }

    change(colors: Colors) {
      const root = this.document.documentElement;
      root.style.setProperty('--bg-color', colors.background);
      this.colors$.next(colors);
    }
}

For a complete demonstration, check out this example: https://stackblitz.com/edit/angular-change-css-variable?file=src/app/app.component.ts

Answer №2

Unfortunately, achieving that is not an option. However, you can utilize style bindings instead.

class CustomComponent {
    customStyles: any;
    constructor(private theme: ThemeColors) {}
    ngOnInit() { this.customStyles = this.theme.defaultPalette; }
}
<div [style.background-color]="customStyles.primaryColor"></div>

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

What could be the reason behind my image displaying correctly in the majority of browsers, yet not in Internet Explorer

The HAML code below is what I have: %header .grid %a{:name => "top"} .logo %a{:href => root_path} =image_tag("logo3.png") .tagline .clearfloat %p Fast Facts About Your Website, Your Competitors And Best ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

Navigate to the top of the page using jQuery

Attempting to implement a simple "scroll jump to target" functionality. I've managed to set it up for all parts except the "scroll to top". The jumping works based on the tag's id, so it navigates well everywhere else, but not to the very top. He ...

Loading an animated SVG sprite file in real-time

Recently, I received an SVG sprite file from our designers to use in my app. The specified convention is to load the sprite at the top of the <body> element and then render icons using a specific code snippet: <svg class="u-icon-gear-dims"> ...

Is there an easy method to compare the CSS styles of a specific section in HTML?

Currently, I am facing an issue where the size of a specific area on my asp.net page changes after a post-back. It seems that the style applied to this area is being altered for some reason. This situation has raised the question in my mind - is there a m ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

Tips for generating a list in Angular2 based on previous selections

import { Component } from '@angular/core'; export class Superhero { name: string; } const SUPERHEROES: Superhero[] = [ { name: 'GK-1' }, { name: 'GK-2' }, { name: 'GK-3' }, { name: 'GK-4&ap ...

When implementing flex-grow 1 on a flex box, the remaining space is not being filled as expected

I am struggling to make the green div fill the remaining space of a flex box container. My goal is to have the top row (blue) adjust its height based on content, and then have the row below (green) take up the rest of the space. However, it seems like the ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

What is the process of integrating an API key into Apollo-Angular in order to retrieve information from the MongoDB Realm GraphQL API?

I have been utilizing the MongoDB realm GraphQL API to retrieve data, while also using Apollo-Angular. However, in order to access the data through the GraphQL API, an API key is required. I have successfully tested this by using Postman and including the ...

Applying a class change in Vue.js upon mounting

How can I make a button element with a .hover property trigger the hover animation as soon as the page loads? I want to apply a class to the button when the page is mounted and then remove it later. What is the best approach for this? I considered using a ...

The delay function in RxJS allows for waiting to return a value until a specific condition is met within a stream and

Currently, I am facing an issue with a method in my application that triggers a server request. This method has access to a stream from the redux-store and needs to execute a callback only when the result of the request is found in the mentioned stream. Th ...

What is the best way to convert the NextJS router.query.id to a string?

As a newcomer to TypeScript and the T3 stack (React Query / Tanstack Query), I am facing an issue with typing companyId as string. I want to avoid having to type companyId as string every time I use it in my code, but I'm struggling to find the best p ...

Ways to manage multiple Observables

Two Observables are being returned from different services, each providing only one value (similar to Observable.just()). In TypeScript, types play a crucial role in this context. Is there a method to determine when both Observables have been resolved (in ...

Optimizing the position of the datepicker dropdown in Boostrap 4

I am currently utilizing Bootstrap 4 (final) with the boostrap-datepicker-plugin 1.7.1. Since Bootstrap 4 no longer uses .input-group-addon elements for the calendar icon, but instead .input-group-prepend and .input-group-append, I made some modificatio ...

How can I incorporate dynamic fields into a Typescript type/interface?

In my Typescript interface, I have a predefined set of fields like this: export interface Data { date_created: string; stamp: string; } let myData: Data; But now I need to incorporate "dynamic" fields that can be determined only at runtime. This me ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...