Angular 5:如何在中央文件中定义调色板

Angular 5: How to define color pallet in a central file

我想在项目的中央文件中声明我的调色板。

目前我正在使用包含地图的 Injectable 来引用我使用过的所有颜色。示例:

@Injectable()

export class COLOR_DICTIONARY {
private static COLOR_MAP: Map<string, string> = new Map<string, string>();

 constructor() {
    COLOR_DICTIONARY.COLOR_MAP.set('primary', '#339988');
 }

 get(key: string) {
    return COLOR_DICTIONARY.COLOR_MAP.get(key);
 }
}

然而,这迫使我在标记中引用所有颜色,而不是直接在 css 中引用 ngStyle

[ngStyle]="{'color': color_dictionary.get('primary')}"

我目前正在对整个网站进行更大规模的重新设计,更改样式文件和标记文件中的样式变得很麻烦。 (甚至 adding/changing/deleting 颜色的打字稿文件)。

如何在中央文件中引用调色板 - 最好是更静态的文件,如 XML 文件或其他可以直接在 css 文件中引用的文件。

我愿意将样式转换为 scss 文件,如果这样会更容易,或者如果它有利于目的。

该项目与 webpack 捆绑在一起,因此也欢迎任何有关如何为此捆绑解决方案的提示。

一种不错的现代方法是使用 css 变量。全球支持不错,已被angular community推荐。

import { Component, Renderer2 } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1> Hello </h1>
    <h2> World </h2>
  `,
  styles: [
    'h1 { color: var(--primary); }',
    'h2 { color: var(--accent); }'
  ]
})
export class AppComponent {

  constructor() { }

  ngOnInit() {
    const colors = new Map([
      ['primary', 'blue'],
      ['accent', 'red'],
    ])

    Array.from(colors.entries()).forEach(([name, value]) => {
      document.body.style.setProperty(`--${name}`, value);
    })

  }
}

Live demo