注入来自服务器的 CSS 个变量名 (Angular 12)

Inject CSS variable names that come form the server (Angular 12)

我正在尝试找到将 css 变量注入 angular 应用程序(当前使用 Angular 12)的最佳解决方案。

这是我正在使用的代码:

 private injectStyles(data: any) {
    const styles = this.document.createElement('STYLE') as HTMLStyleElement;
    styles.id = 'dynamic-css';

    this.test = `:root {      
      --main-bg-color: black;
    }`;
    
    styles.innerHTML = this.test;
    this.renderer.appendChild(this.document.head, styles);
}

此代码在 app.component.ts 文件上执行,效果很好,我可以在整个应用程序中使用此 css 变量。 我现在想要实现的是使用来自服务器的数据扩展 this.test 对象,并应用之前在我的视觉设置模块上设置的这些自定义 css 值。

Css 变量不能有 "" 引号。 "--button-color": "#a86c6c"(这是我从服务器得到的),我想在 this.test 对象上注入这个 属性 而不带引号,但我不能那样做。有什么想法吗?

非常感谢任何帮助, 谢谢

Object.keys是你的朋友

 let dataString = '';
 Object.keys(data).forEach(key => {
    dataString += `${key}: ${data[key]};`
 });
 this.test = `:root {      
  --main-bg-color: black;
  ${dataString}
}`;

如果需要,您可能需要像这样为值添加引号

`dataString += `${key}: "${data[key]};"`