【Angular】想动态地根据数据库的数据更改主题颜色

首先

共有一种根据数据库数据(颜色代码)来更改Angular主题颜色的方法。

环境

    • Angular 8.2.11

 

    Angular Material 8.2.3

声明变量以应用主题颜色到global.css文件。

顺便说一下,根据环境不同,可能不叫global.css,而是style.css。(我使用的是style.css。)
要确认global.css的方法是,查看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文件中添加以下设置。
※关于这里的默认颜色,由于网络速度的影响,颜色的反映可能会延迟,看起来会闪烁,因此最好与背景色相匹配以避免问题。

:root {
    --main-color: #FFF;
    --sub-color: #FFF;
    --accent-color: #FFF;
}

将之前设定的变量应用到想要应用主题颜色的部分。

以下是一个设置的示例。

以下为一个样例设置。

.example-main {
  &__item {
    &__button {
      background-color: var(--main-color);
    }
  }
}

创建用于自定义主题颜色的Service类。

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()里调用这个函数,可以应用主题颜色。

请参照以下中文翻译,只提供一种选项:

– 请拿此作为参考

    Theming Angular apps with CSS Custom Properties
广告
将在 10 秒后关闭
bannerAds