【问题标题】:Angular: How dynamcally change scss variables?Angular:如何动态更改 scss 变量?
【发布时间】:2019-12-10 20:15:13
【问题描述】:

我是 scss 的新手,所以我想知道是否可以使用组件的 Typescript 更改 scss 变量。

所以考虑一下:

html: 
<div (someEvent)="handleEvent($event)"></div>

scss: 
$thememode: 'theme1'; 
$textcolormode: 'nonHover'; 
$colorOpacity: 0.1; 
@mixin someFunction(param1, param2){
    //do scss magic
}

ts: //Here is what I want to do, but dont know to code:
handleEvent(event):void{
   this.scssFile.$thememode = 'theme2'; 
   this.scssFile.$colormode = 'hover'; 
   this.scssFile.$colorOpacity = this.someattribute + this.someServive.$generateAnotherValue(someParam); 
   this.scssFile.@someFunction(23, 'mode1'); 
}

基本上我只是希望能够访问我定义的 scss 变量/mixin。

有没有办法做到这一点?

【问题讨论】:

  • 只使用 CSS 变量。

标签: angular sass scss-mixins


【解决方案1】:

无法从您的 Angular 组件操作 Sass 文件,因为在 Angular 访问您的组件时,Sass 已经编译为 CSS。 您应该使用 NgStyle 和 NgClass 指令来实现这一点。

【讨论】:

    【解决方案2】:

    Scss 是一个预处理器。它是否在编译时转换为常规 CSS。这意味着您无法在运行时修改您的 Scss,因为它不再存在。

    动态管理主题的另一种方法是使用css variables 并动态更新它们。

    【讨论】:

      【解决方案3】:

      正如其他人已经提到的,一个好方法是使用 CSS 变量。即使您必须支持 IE11,这也很好,因为有一个适用于此的 ponyfill。请注意,您也可以混合使用 SCSS 和 CSS 属性,只需定义一些 CSS 属性并在您的 SCSS 定义中使用它们,生成的 CSS 仍将包含 CSS 属性。

      我在我的一个项目中使用了相同的方法,我在运行时从配置文件中解析一些颜色值,然后根据这些值设置 css 属性:

        ngAfterViewInit() {
          const options: any = {
            watch: true,
            preserveStatic: false,
            variables: {
              '--accent': AppConfigService.settings.style.accent,
              '--contrast': AppConfigService.settings.style.contrast,
              '--page-color': AppConfigService.settings.style.pagecolor,
              '--page-contrast': AppConfigService.settings.style.pagecontrast,
              '--text-color': AppConfigService.settings.style.textcolor,
              '--info-color': AppConfigService.settings.style.infocolor,
              '--warn-color': AppConfigService.settings.style.warncolor,
              '--white': AppConfigService.settings.style.white
            }
          };
          cssVars(options);
        }
      

      提到的 ponyfill 是 css-vars-ponyfill

      【讨论】:

        猜你喜欢
        • 2021-05-11
        • 2020-06-22
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 2018-07-04
        • 1970-01-01
        • 2020-02-17
        • 1970-01-01
        相关资源
        最近更新 更多