切换角度材料中的主题5

CSS

西里神奇

2020-03-24

我一直在阅读一些有关此的文章,但它们似乎在几种不同的方式上存在冲突。我希望为角材料的最新版本[5.0.0-rc0] 重新创建与角材料文档站点相同的主题切换

我有两个自定义主题,这是custom-theme.scss,还有light-custom-theme.scss,几乎相同,没有垫子深色主题

@import '~@angular/material/theming';
$custom-theme-primary: mat-palette($mat-blue);
$custom-theme-accent: mat-palette($mat-orange, A200, A100, A400);
$custom-theme-warn: mat-palette($mat-red);
$custom-theme: mat-dark-theme($custom-theme-primary, $custom-theme-accent, $custom-theme-warn);

@include angular-material-theme($custom-theme);

我的styles.scss看起来像这样

@import '~@angular/material/theming';
@include mat-core();
@import 'custom-theme.scss';
@import 'light-custom-theme.scss';
.custom-theme {
  @include angular-material-theme($custom-theme);
}

.light-custom-theme {
  @include angular-material-theme($light-custom-theme);
}

然后在index.html中调用它 <body class="mat-app-background">

当我做一个主题时,一切正常。但是我试图在两者之间切换。将两个主题都添加到angular-cli.json中,light-custom-theme就将接管

"styles": [
  "styles.scss",
  "custom-theme.scss",
  "light-custom-theme.scss"
],

我在其中一个组件中放置了以下代码来处理切换主题

toggleTheme(): void {
  if (this.overlay.classList.contains("custom-theme")) {
    this.overlay.classList.remove("custom-theme");
    this.overlay.classList.add("light-custom-theme");
  } else if (this.overlay.classList.contains("light-custom-theme")) {
    this.overlay.classList.remove("light-custom-theme");
    this.overlay.classList.add("custom-theme");
  } else {
    this.overlay.classList.add("light-custom-theme");
  }
}

但是无论何时运行,主题都保持不变。对于它的价值,在overlay.classList中的位置0处已经有一个“ cdk-overlay-container”对象。

0:"cdk-overlay-container"
1:"custom-theme"
length:2
value:"cdk-overlay-container custom-theme" 

我不确定如何调试它,因为角材文档不会给我太多工作,任何帮助将不胜感激!

谢谢!

第3536篇《切换角度材料中的主题5》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
LEY村村 2020.03.24

您可以随时检查https://material.angular.io/中主题选择器的实现方式,并执行相同的https://github.com/angular/material.angular.io/tree/master/src/app / shared / theme-picker这样,您将拥有永久的解决方案,以防万一任何重大更改都可以随时查找材料文档来解决。

凯卡卡西凯 2020.03.24

参考@Edric的解决方案

使用本地存储来保留选定的主题

这是我的Github链接,在这里我更新了工作代码: 〜Angular Material Theme Changer

希望这也有帮助。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android