はじめに
DBのデータ(カラーコード)を元にAngularのテーマカラーを変更する方法を共有していく。
環境
- Angular 8.2.11
- Angular Material 8.2.3
global.css
にテーマカラーを適用するための変数を宣言
ちなみに環境によってはglobal.css
という名前ではなく、style.css
かもしれない。(自分はstyle.css
だった。)
global.css
の確認方法としては、angular.json
のこの箇所↓
angular.json
{
"projects": {
"hoge-project": {
...
"architect": {
"build": {
...
"options": {
...
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/styles.css"
],
},
}
}
}
}
}
ここに指定されているsrc/style.css
というのがglobal.css
にあたるものだ。
このstyle.css
に以下の設定を追加。
※ここのデフォルトカラーに関しては、ネットワークの速度によってはどうしても色の反映が遅れてしまい、ちらついたように見えてしまうため背景色と合わせたほうが無難。
style.css
:root {
--main-color: #FFF;
--sub-color: #FFF;
--accent-color: #FFF;
}
テーマカラーを適用したい箇所に、先ほど設定した変数を当てる
以下は設定例
example.scss
.example-main {
&__item {
&__button {
background-color: var(--main-color);
}
}
}
カスタムテーマカラー用のServiceクラスを作成
theme-color.service.ts
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
interface ThemeColor {
mainColor: string;
subColor?: string;
accentColor?: string;
}
@Injectable({
providedIn: 'root',
})
export class ThemeColorService {
constructor(private http: HttpClient) {}
public async initialize() {
const { mainColor } = await this.http
.get<ThemeColor>('theme-color')
.toPromise();
document.documentElement.style.setProperty('--main-color', mainColor);
}
}
重要なのはこの部分。
document.documentElement.style.setProperty('--main-color', mainColor);
これをapp.component.ts
のngOnInit()
とかで呼んであげることでテーマカラーが適用される。