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

Jon*_*aem 1 css sass styling color-palette angular

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

目前我正在使用一个包含地图的 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);
 }
}
Run Code Online (Sandbox Code Playgroud)

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

[ngStyle]="{'color': color_dictionary.get('primary')}"
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Tom*_*ula 6

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

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);
    })

  }
}
Run Code Online (Sandbox Code Playgroud)

现场演示