角度5:如何在中央文件中定义调色板 [英] Angular 5: How to define color pallet in a central file

查看:82
本文介绍了角度5:如何在中央文件中定义调色板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的项目的中央文件中声明我的颜色托盘.

I want to declare my color pallet in a central file in my project.

当前,我正在使用一个包含贴图的Injectable来引用我所有使用过的颜色.示例:

Currently I am using an Injectable which contains a map, to reference all my used colors. Example:

@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中引用标记中的所有颜色

However this forces me to reference all the colors in the markup instead of directly in the css, with ngStyle

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

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

I am currently doing a larger redesign of the whole site, and it is becoming a hassle to change styling in both styling files & markup files. (And even typescript files for adding/changing/deleting colors).

我如何在中央文件中引用调色板-最好是更静态的文件(如XML文件或类似文件),可以直接在css文件中引用.

How can I reference the color pallet in a central file - preferably a more static file like a XML file or something, which can be referenced directly in the css files.

我愿意将样式转换为scss文件,如果这样可以使其变得更容易,或者对目的有益.

I am willing to convert the styling to scss files if that would make it easier, or if it's beneficial to the purpose.

该项目与webpack捆绑在一起,因此,有关如何捆绑此解决方案的任何技巧也将受到赞赏.

The project is bundled with webpack, so any tips on how to bundle the solution for this is also appreciated.

推荐答案

一种不错的现代方法是使用css变量.全球支持相当不错,角度社区建议.

A nice and modern way, would be to use css variables. Global support is pretty good, and it has been recommended by the 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);
    })

  }
}

实时演示

这篇关于角度5:如何在中央文件中定义调色板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆