abhay tripathi
abhay tripathi

Reputation: 4032

Change css variables dynamically in angular

In my angular project, I have some css variables defined in top level styles.scss file like this. I use these variable at many places to keep the whole theme consistent.

:root {
  --theme-color-1: #f7f7f7;
  --theme-color-2: #ec4d3b;
  --theme-color-3: #ffc107;
  --theme-color-4: #686250;

  --font-weight: 300
}

How can I update values of these variables dynamically from app.component.ts ? And What is the clean way to do this in angular ?

Upvotes: 25

Views: 34054

Answers (3)

AlexElin
AlexElin

Reputation: 1589

Starting with Angular v9 you can use the style binding to change a value of a custom property

<app-component-name [style.--theme-color-1]="'#CCC'"></app-component-name>

Upvotes: 15

Serkan KONAKCI
Serkan KONAKCI

Reputation: 1360

Some examples add variables directly to html tag and it seem in the element source as a long list. I hope this helps to you,


class AppComponent {
  private variables=['--my-var: 123;', '--my-second-var: 345;'];

  private addAsLink(): void {
    const cssVariables = `:root{ ${this.variables.join('')}};
    const blob = new Blob([cssVariables]);
    const url = URL.createObjectURL(blob);
    const cssElement = document.createElement('link');
    cssElement.setAttribute('rel', 'stylesheet');
    cssElement.setAttribute('type', 'text/css');
    cssElement.setAttribute('href', url);
    document.head.appendChild(cssElement);
  }
}

Upvotes: 0

Gautam Naik
Gautam Naik

Reputation: 9368

You can update them using

 document.documentElement.style.setProperty('--theme-color-1', '#fff');

If u want to update many values, then create a object

 this.styles = [
      { name: 'primary-dark-5', value: "#111" },
      { name: 'primary-dark-7_5', value: "#fff" },
    ];

 this.styles.forEach(data => {
      document.documentElement.style.setProperty(`--${data.name}`, data.value);
 });

The main thing here is document.documentElement.style.setProperty. This line allows you to access the root element (HTML tag) and assigns/overrides the style values.

Note that the names of the variables should match at both places(css and js files)


if you don't want to use document API, then you can use inline styles on HTML tag directly

    const styleObject = {};

    this.styles.forEach(data => {
      styleObject[`--${data.name}`] = data.value;
    });

Then In your template file using ngStyle (https://angular.io/api/common/NgStyle)

Set a collection of style values using an expression that returns key-value pairs.

<some-element [ngStyle]="objExp">...</some-element>
<html [ngStyle]="styleObject" >...</html>  //not sure about quotes syntax

Above methods do the same thing, "Update root element values" but in a different way.

When you used :root, the styles automatically got attached to HTML tag

Upvotes: 35

Related Questions