Angular Material2为不同的构建/环境使用不同的主题(颜色)

时间:2018-06-11 09:46:15

标签: angular angular-cli angular-material2 angular6 angular-cli-v6

我有一个Angular6应用程序,它使用CLI和material2以及自定义主题。现在,对于另一个客户,我想使用相同的应用程序,但使用不同的颜色。我怎样才能做到这一点?我不想维护第二个代码库,所以它必须与我认为的构建和/或环境有关吗?

我在[{1}}中导入的主题:

styles.scss

2 个答案:

答案 0 :(得分:1)

您可以采用的一种方法是使用基本的CSS类。在主题文件中,定义不同的主题:

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

@include mat-core();

// Define a default theme
$light-default-primary: mat-palette($mat-blue);
$light-default-accent:  mat-palette($mat-blue-grey, A200, A100, A400);
$light-default-warn:    mat-palette($mat-red);
$light-default-theme:   mat-light-theme($light-default-primary, $light-default-accent, $light-default-warn);
@include angular-material-theme($light-default-theme);

.light-blue-theme {

  $light-blue-primary: mat-palette($mat-blue);
  $light-blue-accent:  mat-palette($mat-blue-grey, A200, A100, A400);
  $light-blue-warn:    mat-palette($mat-red);
  $light-blue-theme:   mat-light-theme($light-blue-primary, $light-blue-accent, $light-blue-warn);

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

.dark-theme {

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

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

并在您的evnironments.ts文件中定义客户:(我猜每个客户都需要单独的环境)

export const client = {
 clientName: 'xxx'
}

在您的组件中,您可以设置当前客户:

export class AppComponent { 
  public clientName: string = this.env.client.clientName; // imported from environments.ts
...

然后在您的模板中,您可以将相关的类添加到主容器中:

<div [class.light-blue-theme]="clientName === 'xxx'" [class.dark-theme]="clientName === 'yyy'">
  ...
</div>

答案 1 :(得分:1)

如果您使用的是角度6,则可以使用angular.json中的{ "projects": { "myproject": { "architect": { "build": { "configurations": { "production": { "fileReplacements": [ { "replace": "projects/customer/src/environments/environment.ts", "with": "projects/customer/src/environments/environment.prod.ts" }, { "replace": "projects/customer/src/themes/theme.scss", "with": "projects/customer/src/themes/theme.prod.scss" } ] } } } } } } } 配置部分。 使用此方法,只有在为特定环境构建时,才能使用文件customer1.theme.scss替换文件theme.scss。

这是一个例子:

"language": {
    "type": "text",
    "fields": {
      "keyword": {
        "type": "keyword",
        "ignore_above": 256
      }
    }
  },
"booktitle": {
  "type": "text",
  "fields": {
    "keyword": {
      "type": "keyword",
      "ignore_above": 256
    }
  }
},
"booksubtitle": {
  "type": "text",
  "fields": {
    "keyword": {
      "type": "keyword",
      "ignore_above": 256
    }
  }
},
"bookdescription": {
  "type": "text",
  "fields": {
    "keyword": {
      "type": "keyword",
      "ignore_above": 256
    }
  }
}