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

只谈情不闲聊 提交于 2019-12-11 05:06:19

问题


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

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

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).

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.

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

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


回答1:


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

  }
}

Live demo



来源:https://stackoverflow.com/questions/49843157/angular-5-how-to-define-color-pallet-in-a-central-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!