Angular - Как получить переменную S CSS в style.s css по javascript в компоненте? - PullRequest
0 голосов
/ 14 июля 2020

У меня есть приложение с Angular 9, использующим Angular Материал, в котором есть 2 темы (темная и светлая). Они определены так в файле style.s css:

$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)};
}

И чтобы установить тему для приложения, я просто установил ее как класс элемента body:

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

У меня есть небольшой компонент Angular, которому нужно будет получить значение из - test-color as Hex color , который зависит от того, какая (темная или светлая тема) наносится на элемент body ).

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 ]

0 голосов
/ 14 июля 2020

Я нашел способ сделать это, создав класс обслуживания

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;
  }
}

и в компоненте я могу получить вычисленный цвет следующим образом

constructor(private cssService:CssService) { }

ngOnInit(): void {
    const fontColor = this.cssService.getAttributeValue("--text-color");
}
0 голосов
/ 14 июля 2020

- цвет текста это настраиваемые css переменные или свойства, поэтому, если вы хотите установить переменную из angular, сделайте что-то вроде ниже: - `

 export class ChartComponent implements OnInit {
  textColor: string;

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

поэтому присвойте значение свойству цвета текста примерно так и используйте его в html, как показано ниже: -

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

, поэтому, используя этот * ngStyle, вы можете установить свойство компонента angular на css пользовательская переменная.

Надеюсь, это поможет.

...