如何动态切换主题,角材质18

问题描述 投票:0回答:1

我使用 Angular Material 实用程序创建了 2 个自定义主题。

ng generate @angular/material:m3-theme

我在

styles.scss
中使用这两个主题,就像这样。

@use '@angular/material' as mat;

@use './m3-theme';
@use './m4-theme';
@include mat.core();
.alternate-theme-m3 {
        @include mat.core-theme(m3-theme.$light-theme);
        @include mat.button-theme(m3-theme.$light-theme);
        background-color: mat.get-theme-color(m3-theme.$light-theme, secondary, 50) !important;
    }
    
    .alternate-theme-m4 {
        @include mat.core-theme(m4-theme.$light-theme);
        @include mat.button-theme(m4-theme.$light-theme);
        background-color: mat.get-theme-color(m4-theme.$light-theme, secondary, 50) !important;
    }

在我的组件中,我正在切换类以获取样式。

Q1:这是正确的方法,还是应用自定义这些和动态主题切换的任何更好的方法。

Q2: 垫子按钮变得很圆,我无法使其变得小圆。我怎样才能实现这一目标?

谢谢。

angular angular-material
1个回答
0
投票

下面的例子:

import { Injectable } from '@angular/core';
export enum ColorScheme {
  Deep_Purple_And_Amber = 'deeppurple-amber.css',
  Indigo_And_Pink = 'indigo-pink.css',
  Pink_And_Bluegrey = 'pink-bluegrey.css',
  Purple_And_Green = 'purple-green.css',
}


@Injectable()
export class ColorSchemeService {
  public currentColorScheme: ColorScheme|null = null;
  private key = 'colorScheme';

  initColorScheme(): void {
    const localColorScheme = localStorage.getItem(this.key) as ColorScheme;
    this.changeColorScheme(localColorScheme || ColorScheme.Deep_Purple_And_Amber);
  }

  changeColorScheme(colorScheme: ColorScheme): void {
    if (this.currentColorScheme === colorScheme) return;
    localStorage.setItem(this.key, colorScheme);
    const oldElement = document.getElementById(this.key);
    if (oldElement) oldElement.remove();
    this.currentColorScheme = colorScheme;
    const head = document.getElementsByTagName('head')[0];
    const link = document.createElement('link');
    link.id = this.key;
    link.rel = 'stylesheet';
    link.href = 'assets/css/material/' + colorScheme;
    head.insertBefore(link, head.lastChild); // обязательно после style.css чтобы переопределялись цвета все

    const body = document.getElementsByTagName('body')[0];
    body.classList.add(colorScheme.replace('.css', ''));
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.