角度2材料动态主题

时间:2017-03-14 12:35:32

标签: angular themes angular-material

我创建了自己的scss主题并在angular-cli.json中声明了它,一切正常。

现在我需要动态更改主题。

我试图在angular-cli.json中添加第二个主题,但正如预期的那样它会覆盖第一个主题。

所以也许有一个选择是从angular-cli.json中删除主题声明,并且有两个组件,每个组件都有自己的scss样式,一个覆盖另一个,它们之间的唯一区别是styleUrls。

或者是否有其他推荐的动态加载scss的方法?

6 个答案:

答案 0 :(得分:25)

从Angular 5.1开始,这就是我实现动态主题更改的方式。

*编辑:这仍然适用于Angular 7 +

使用可编辑示例 - https://stackblitz.com/edit/dynamic-material-theming

在我的theme.scss文件中,我包含一个默认主题(注意它不是保存在类名下 - 这是Angular将它用作默认值),然后是一个明暗主题。 / p>

<强> theme.scss

@import '~@angular/material/theming';
@include mat-core();

// Typography
$custom-typography: mat-typography-config(
  $font-family: Raleway,
  $headline: mat-typography-level(24px, 48px, 400),
  $body-1: mat-typography-level(16px, 24px, 400)
);
@include angular-material-typography($custom-typography);

// Default colors
$my-app-primary: mat-palette($mat-teal, 700, 100, 800);
$my-app-accent:  mat-palette($mat-teal, 700, 100, 800);

$my-app-theme: mat-light-theme($my-app-primary, $my-app-accent);
@include angular-material-theme($my-app-theme);

// Dark theme
$dark-primary: mat-palette($mat-blue-grey);
$dark-accent:  mat-palette($mat-amber, A200, A100, A400);
$dark-warn:    mat-palette($mat-deep-orange);

$dark-theme:   mat-dark-theme($dark-primary, $dark-accent, $dark-warn);

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

// Light theme
$light-primary: mat-palette($mat-grey, 200, 500, 300);
$light-accent: mat-palette($mat-brown, 200);
$light-warn: mat-palette($mat-deep-orange, 200);

$light-theme: mat-light-theme($light-primary, $light-accent, $light-warn);

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

在app.component文件中,我包含来自@ angular / cdk / overlay的OverlayContainer。你可以在这里找到Angular的文档https://material.angular.io/guide/theming;虽然他们的实施有点不同。请注意,我还必须在App.module中包含OverlayModule作为导入。

在我的app.component文件中,我还将@HostBinding('class') componentCssClass;声明为变量,用于将主题设置为类。

<强> app.component.ts

import {Component, HostBinding, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Version } from './classes/version';
import { OverlayContainer} from '@angular/cdk/overlay';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {

  constructor(private http: HttpClient, public overlayContainer: OverlayContainer) {}

  title = 'app';
  version: Version;
  @HostBinding('class') componentCssClass;

  ngOnInit() {
    this.getVersion();
  }

  onSetTheme(theme) {
    this.overlayContainer.getContainerElement().classList.add(theme);
    this.componentCssClass = theme;
  }

  getVersion() {
    this.http.get<Version>('/api/version')
      .subscribe(data => {
        this.version = data;
      });
  }

}

<强> app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpClientModule } from '@angular/common/http';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';

import { AppComponent } from './app.component';

import { OverlayModule} from '@angular/cdk/overlay';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MatCardModule,
    MatButtonModule,
    OverlayModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

最后,从您的视图中调用onSetTheme函数。

<强> app.component.html

<button mat-raised-button color="primary" (click)="onSetTheme('default-theme')">Default</button>
<button mat-raised-button color="primary" (click)="onSetTheme('dark-theme')">Dark</button>
<button mat-raised-button color="primary" (click)="onSetTheme('light-theme')">Light</button>

您可以考虑使用observable,以便功能更具动态性。

答案 1 :(得分:5)

我在Change Material design theme for Angular 2找到了答案。 https://github.com/jelbourn/material2-app有一个很好的GIT示例。

所以我使用相同的单个scss主题文件,但我为它添加了一个新主题的新类:

.m2app-dark {
  $dark-primary: md-palette($md-pink, 700, 500, 900);
  $dark-accent:  md-palette($md-blue-grey, A200, A100, A400);
  $dark-warn:    md-palette($md-deep-orange);
  $dark-theme: md-dark-theme($dark-primary, $dark-accent, $dark-warn);
  @include angular-material-theme($dark-theme);
}

这个在html中使用,是否有效取决于布尔值:

 <md-sidenav-layout [class.m2app-dark]="isDarkTheme">

答案 2 :(得分:1)

您可以在运行时根据当前主题在body标签上添加或删除css类(包括素材主题)来在主题之间切换。

例如第1步。

在HTML文件的body标签中添加ID,以便您可以逐个文件地归档。

<body id="themeTag">
<app-root></app-root>
</body>

第2步。

在您的scss文件中创建第二个主题,该文件包含在angular.json中(角度6)和.angular-cli.json中,其角度版本低于6。

@include mat-core();
$primary: mat-palette($mat-blue);
$accent: mat-palette($mat-yellow);
$warn: mat-palette($mat-red);

$light-theme: mat-light-theme($primary, $accent, $warn);

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

$dark-theme: mat-dark-theme($primary, $accent, $warn);

.dark-theme { // css class for dark theme
  @include angular-material-theme($dark-theme);
}

第3步。

在按钮上单击更改正文标签的类别

toggleTheme(){
   this.isDarkTheme = !this.isDarkTheme;
   if(this.isDarkTheme){
     /* here themeTag is id of body tag and dark-theme is css class created in theme file */
     document.getElementById('themeTag').classList.add('dark-theme');
   }else{
     document.getElementById('themeTag').classList.remove('dark-theme');
   }
}

答案 3 :(得分:1)

谢谢@ K.Waite。我使用了his/her answer。我试图改善它。最重要的修改是使用 .replace() 代替 .add() (在中使用 classList > setTheme() 方法)。您还可以在下面看到其他一些功能:


enter image description here

stackblitz here


最重要的部分:

在您的styles.scss 中(如果有,则为themes.scss):

@import '~@angular/material/theming';

@include mat-core();

@mixin define-css-classes($theme) {
    @include angular-material-theme($theme);

    $primary: map-get($theme, primary);
    $accent: map-get($theme, accent);
    $warn: map-get($theme, warn);
    $background: map-get($theme, background);
    $foreground: map-get($theme, foreground);

    // CSS THEME-DEPENDENT-STYLES ARE HERE:
    .theme-dependent-colors {
        background: mat-color($primary);
        color: mat-color($accent);
    }
}

/**
* Define your custom themes in this map. 
* The `key` of each member is the name of CSS class for that theme. 
* To better understand the schema of the map, see `@each` loop below and especially pay attention to `map-has-key()` functions.
*/ 
$app-themes: (
        indigo-pink : (primary-base: $mat-indigo, accent-base: $mat-pink),
        deeppurple-amber: (primary-base: $mat-deep-purple, accent-base: $mat-amber),
        pink-bluegrey : (primary-base: $mat-pink, accent-base: $mat-blue-gray, is-dark: true),
        purple-green : (primary-base: $mat-purple, accent-base: $mat-green, is-dark: true),
);

@each $css-class, $theme in $app-themes {
    $primary: if(map-has-key($theme, primary), map-get($theme, primary), mat-palette(map-get($theme, primary-base)));

    $accent: if(map-has-key($theme, accent), map-get($theme, accent), mat-palette(map-get($theme, accent-base)));

    $warn: if(map-has-key($theme, warn), map-get($theme, warn), mat-palette(
            if(map-has-key($theme, warn-base), map-get($theme, warn-base), $mat-red)
    ));

    .#{$css-class} {
        @include define-css-classes(mat-light-theme($primary, $accent, $warn));
    }

    .#{$css-class}-dark {
        @include define-css-classes(mat-dark-theme($primary, $accent, $warn));
    }

    .theme-primary.#{$css-class} {
        background-color: mat-color($primary);
    }

    ...
}

在打字稿中(请参见here

import {Component, HostBinding} from '@angular/core';
import {OverlayContainer} from "@angular/cdk/overlay";

const THEME_DARKNESS_SUFFIX = `-dark`;

export class AppComponent {
    @HostBinding('class') activeThemeCssClass: string;
    isThemeDark = false;
    activeTheme: string;

    setTheme(theme: string, darkness: boolean = null) {
        if (darkness === null)
            darkness = this.isThemeDark;
        else if (this.isThemeDark === darkness) {
            if (this.activeTheme === theme) return;
        } else
            this.isThemeDark = darkness;

        this.activeTheme = theme;

        const cssClass = darkness === true ? theme + THEME_DARKNESS_SUFFIX : theme;

        const classList = this.overlayContainer.getContainerElement().classList;
        if (classList.contains(this.activeThemeCssClass))
            classList.replace(this.activeThemeCssClass, cssClass);
        else
            classList.add(cssClass);

        this.activeThemeCssClass = cssClass;
    }

    constructor(overlayContainer: OverlayContainer) {
        this.setThemeClass('indigo-pink', false); // Default theme
    }
}

请参阅stackblitz中的其他内容。


注意事项:在我的情况下,向应用程序添加8个动态材质主题(4个灯光+ 4个暗度),将构建的styles.css的大小增加了~420 kB(相对于一个静态材质主题) !

答案 4 :(得分:0)

@K Waite(评论不足。)

从Angular 8开始(可能更早吗?)

我发现有必要添加额外的行declare function will(result: Promise<T>): Promise<[any, T]> export default will 。在测试过程中,我观察到将动态主题更改应用于“模态弹出窗口”时,“模态窗口”将仅应用classList中的 last 主题。因此,从深色主题切换到浅色主题可能会导致错误状态。

使用两个元素(解决了classList.remove(this.componentCssClass);和当前活动的主题)来强制执行课程列表

default-theme

答案 5 :(得分:0)

Angular 8解决方案,提供scss,Angular材料和服务- 1.创建您的自定义scss文件。

@import '~@angular/material/theming';
   @include mat-core();
   .dark-theme{
    $custom-theme-primary: mat-palette($mat-yellow);
    $custom-theme-accent:mat-palette($mat-grey);
    $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);
    }

    $custom-theme-primary: mat-palette($mat-yellow);
    $custom-theme-accent:mat-palette($mat-grey);
    $custom-theme-warn: mat-palette($mat-red);
    $custom-theme: mat-light-theme($custom-theme-primary, $custom-theme-accent, $custom-theme-warn);
    @include angular-material-theme($custom-theme);
  1. 以您的样式导入自定义scss。scss-

    @import'./reset.css'; @import'./custom-theme.scss'; @import“ ../ node_modules / font-awesome / css / font-awesome.css”;

  2. 创建一个服务以设置主题并获取当前主题-

    从“ @ angular / core”导入{Injectable}; 从'rxjs'导入{Subject,BehaviorSubject};

    @Injectable({   providerIn:'root' }) 导出类ThemeChangeService {   private _darkTheme = new BehaviorSubject(true);   isDarkTheme = this._darkTheme.asObservable();   builder(){}

    setDarkTheme(isDarkTheme:Boolean){     this._darkTheme.next(isDarkTheme);   } }

  3. 使用setDarkTheme()通过注入服务在任意位置设置主题。

  4. 可观察到_darkTheme来获取当前选定的主题。
  5. 将服务注入app.component.ts-

    从'./services/theme-change.service'导入{ThemeChangeService}; 从'@ angular / core'导入{Component,OnInit}; 从'rxjs'导入{Observable};

    @Component({   选择器:“ app-root”,   templateUrl:“ ./ app.component.html”,   styleUrls:['./ app.component.scss'] }) 导出类AppComponent实现OnInit {   title ='app';   isDarkTheme:Observable;

    构造函数(私有themeChangeService:ThemeChangeService){     this.isDarkTheme = this.themeChangeService.isDarkTheme;   }   OnInit(){

    }

    }

  6. 使用ngClass指令更改CSS类,您就完成了     

    <app-main [ngClass]="{'dark-theme': isDarkTheme | async}"></app-main>