1
votes

I have an application with Angular 9 using Angular Material, which has 2 themes (dark and light). They are defined like this in the style.scss file:

$rasd-dark-text-color: mat-palette($mat-grey, 300);
$rasd-light-text-color: mat-palette($mat-grey, 800);

.rasd-dark {
   --text-color: #{mat-color($rasd-dark-text-color)};
}

.rasd-light {
   --text-color: #{mat-color($rasd-light-text-color)};
}

And to set the theme for the application, I just set it as a class of the body element:

<body class="mat-typography rasd-dark">
    <app-root></app-root>
</body>

I have a small Angular component which will need to get the value from --test-color as Hex color which depends on which (dark or light theme is applied on the body element).

export class ChartComponent implements OnInit {
    textColor: string;
    
    ngOnInit(): void {
      // (!!!) How can I set the value for textColor from --test-color in SCSS?
      // e.g: after setting, the value of textColor is #001100
    }
}
2

2 Answers

0
votes

--text-color this is the custom css variables or properties so if you want to set the variable from angular do something like below :- `

 export class ChartComponent implements OnInit {
  textColor: string;

  ngOnInit(): void {
     this.textColor = '#ffffff'; // any colour  
   }
}`

so assign the value to the text colour property something like this and consumed in the html like below :-

<body class="mat-typography rasd-dark">
<app-root *ngStyle="{'--text-color':textColor}"></app-root>

so using this *ngStyle you can set the angular component property to the css custom variable.

Hope it will help.

0
votes

I found a way to do this by creating a service class

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

@Injectable({
  providedIn: 'root'
})
export class CssService {

  DARK_THEME = "ras-dark";
  LIGHT_THEME = "ras-light";

  constructor() { }

  /**
   * Get the set theme (dark / light) from body element's class list
   */
  getThemeName(): string {
    const classNames = document.body.className.split(' ');
    let themeName = this.DARK_THEME;
    classNames.forEach(element => {
      if (element === this.LIGHT_THEME) {
        themeName = this.LIGHT_THEME;
        return;
      }
    });

    return themeName;
  }

  /**
   * Get an attribute value of a theme class (e.g: --text-color of ras-dark class)
   */
  getAttributeValue(attributeName):string {
    const themeName = this.getThemeName();
    const element = document.getElementsByClassName(themeName)[0];
    const attributeValue = window.getComputedStyle(element,null).getPropertyValue(attributeName);

    return attributeValue;
  }
}

and in the component, I can get the computed color like this

constructor(private cssService:CssService) { }

ngOnInit(): void {
    const fontColor = this.cssService.getAttributeValue("--text-color");
}