Angular:如何动态更改 scss 变量? [英] Angular: How dynamcally change scss variables?

查看:82
本文介绍了Angular:如何动态更改 scss 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 scss 的新手,所以我在犹豫是否可以使用组件的 Typescript 更改 scss 变量.

Im new to scss so I was waondering if I can change scss variables using the Typescript of a component for example.

所以考虑一下:

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.

Basically I just want to be able to access the scss variables/mixins I define.

有没有办法做到这一点?

Is there a way to do that?

推荐答案

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

As some others already mentioned, a good way is to use CSS variables. Even if you have to support IE11 this is fine, as there's a ponyfill that works for this. Please note that you can also mix the usage of SCSS and CSS properties, just define some CSS properties and use them in your SCSS definitions, the generated CSS will still contain the CSS properties.

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

I use the very same approach in a project of mine, where I parse some colors values from a configuration file at runtime, and then set the css properties according to those values:

  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

The mentioned ponyfill is css-vars-ponyfill

这篇关于Angular:如何动态更改 scss 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆