以角度动态更改css变量

abh*_*thi 6 css typescript css-variables angular

在我的 angular 项目中,我在这样的顶级styles.scss文件中定义了一些 css 变量。我在很多地方使用这些变量来保持整个主题的一致性。

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

  --font-weight: 300
}
Run Code Online (Sandbox Code Playgroud)

如何从app.component.ts动态更新这些变量的值?在 angular 中做到这一点的干净方法是什么?

Ale*_*lin 12

从 Angular v9 开始,您可以使用样式绑定来更改自定义属性的值

<app-component-name [style.--theme-color-1]="'#CCC'"></app-component-name>
Run Code Online (Sandbox Code Playgroud)


Gau*_*aik 10

您可以使用更新它们

 document.documentElement.style.setProperty('--theme-color-1', '#fff');
Run Code Online (Sandbox Code Playgroud)

如果你想更新很多值,那么创建一个对象

 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);
 });
Run Code Online (Sandbox Code Playgroud)

这里的主要内容是document.documentElement.style.setProperty。此行允许您访问根元素(HTML 标记)并分配/覆盖样式值。

请注意,变量的名称应在两个位置(css 和 js 文件)匹配


如果你不想使用文档 API,那么你可以直接在 HTML 标签上使用内联样式

    const styleObject = {};

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

然后在您的模板文件中使用 ngStyle (https://angular.io/api/common/NgStyle)

使用返回键值对的表达式设置样式值集合。

<some-element [ngStyle]="objExp">...</some-element>
Run Code Online (Sandbox Code Playgroud)
<html [ngStyle]="styleObject" >...</html>  //not sure about quotes syntax
Run Code Online (Sandbox Code Playgroud)

上述方法做同样的事情,“更新根元素值”,但以不同的方式。

使用时:root,样式会自动附加到 HTML 标记

  • 谢谢,但我不想直接使用 DOM api。这就是为什么我问第二个问题关于干净/有角度的方式。 (2认同)