根据路线/组件使用不同的主题

时间:2018-05-26 14:20:07

标签: angular typescript angular-material

我试图在整个应用程序中使用一个主题,除了一个页面,我想加载另一个主题。

到目前为止,在我的main.scss中,我包含了一个主题

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

$myapp-primary: mat-palette($mat-light-green, 50);
$myapp-accent:  mat-palette($mat-light-green);

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

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

正如您所看到的,我向主题声明了$myapp-light-theme$myApp-dark-theme,并使用$myapp-light-theme作为主要主题。我试图在我的home.component(加载到<router-outlet></router-outlet>)中切换主题是将代码放入组件样式(home.component.scss):

@import '~@angular/material/theming';
@import "../../styles/angular-material-theme";
@include angular-material-theme($myapp-dark-theme);

但这并没有像我预期的那样奏效。它甚至可能实现我想要实现的目标吗?

1 个答案:

答案 0 :(得分:2)

解决方案是将自定义主题包装到额外的类中:

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

在我要打开自定义主题的组件中:

  constructor(private overlayContainer: OverlayContainer, @Inject(DOCUMENT) private document: Document) {
    overlayContainer.getContainerElement().classList.add('dark-theme');
    document.body.classList.add('dark-theme');
  }

  public ngOnDestroy(): void {
    this.document.body.classList.remove('dark-theme');
    this.overlayContainer.getContainerElement().classList.remove('dark-theme');
  }