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

问题描述 投票:1回答:1

我想在我的项目的中心文件中声明我的颜色托盘。

目前我正在使用包含地图的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);
 }
}

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

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

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

如何在中央文件中引用颜色托盘 - 最好是更加静态的文件,如XML文件或其他东西,可以直接在css文件中引用。

我愿意将样式转换为scss文件,如果这样可以使它更容易,或者它是否有益于目的。

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

css angular sass styling color-palette
1个回答
4
投票

一个不错的现代方法,就是使用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

© www.soinside.com 2019 - 2024. All rights reserved.