1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Angular】DBのデータを元にテーマカラーを動的に変更したい

Posted at

はじめに

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.tsngOnInit()とかで呼んであげることでテーマカラーが適用される。

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?