角度5材料更改自定义组件主题

时间:2018-04-14 05:51:15

标签: angular themes angular5 angular-material2

我很难与主题斗争。我的要求是动态改变主题。对于默认组件,它似乎工作正常。但对于自定义组件我无法理解。以下是实施:

我有一个 styles.scss

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

.widget-para-title {
    font-size: small;
    margin-top:10px;
    color:#4A90E2;
    font-weight:bold;
    margin-bottom:0px;
    padding: 5px;
    font-family: Roboto,"Helvetica Neue",sans-serif;
}

** theme.scss **

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

@include mat-core();

$custom-primary: mat-palette($mat-blue-grey,500);
$custom-accent:  mat-palette($mat-lime, 100);
$custom-warn:    mat-palette($mat-red);
$custom-theme: mat-light-theme($custom-primary, $custom-accent, $custom-warn);

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


//Orange theme
$ora-primary: mat-palette($mat-orange, 800);
$ora-accent:  mat-palette($mat-grey, 200);
$ora-warn:    mat-palette($mat-red);
$ora-theme: mat-light-theme($ora-primary, $ora-accent);

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


//green theme
$green-primary: mat-palette($mat-green, 800);
$green-accent:  mat-palette($mat-grey, 200);
$green-warn:    mat-palette($mat-red);
$green-theme: mat-light-theme($green-primary, $green-accent);

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

我正在使用以下内容即时更改主题 的 app.component.ts

setTheme(theme:string){
      //var theme='green-theme'
      this.overlayContainer.getContainerElement().classList.add(theme);
      this.componentCssClass = theme;
  }

我遇到的问题是,在styles.css中,颜色当前是硬编码的,应该与当前主题的原色值相同。那么我需要在上面的代码中进行哪些更改才能使其正常工作?

1 个答案:

答案 0 :(得分:0)

目前,最佳做法是为您想要主题的每个组件创建一个mixin。

@mixin widget-theme($theme) {
  $primary: map-get($theme, primary);

  .widget-para-title {
      color: mat-color($primary);
      // other styles
    }
  }

@include widget-theme($custom-theme);

.green-theme {
   @include widget-theme($green-theme);
 }

.ora-theme {
   @include widget-theme($ora-theme);
 }

详细了解theming your own components