如何根据深色或浅色主题更改颜色 - Angular Material

时间:2021-07-07 12:28:53

标签: angular angular-material

在我的应用中,我有一个浅色主题和一个深色主题。 我正在尝试为自定义组件设置样式,以便颜色取决于它是深色主题还是浅色主题。这是我在自定义组件 scss 中的代码:

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

@mixin app-toolbar-theme($theme) {
    $accent: map-get($theme, accent);
    $primary: map-get($theme, primary);
    $warn: map-get($theme, warn);

    .mat-toolbar {
        background: //if dark theme 'red', if light theme 'blue'
    }
}

有没有办法根据我是深色主题还是浅色主题来更改工具栏的背景?

2 个答案:

答案 0 :(得分:1)

使用 prefers-color-scheme 媒体查询:

@media (prefers-color-scheme: dark) {
    .mat-toolbar {
        background: red;
    }
}

@media (prefers-color-scheme: light) {
    .mat-toolbar {
        background: blue;
    }
}

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme

答案 1 :(得分:0)

我找到了如何做到这一点。 我创建了两个 mixin 组件主题,将浅色添加到浅色主题中,将深色添加到深色主题中。

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

@mixin app-toolbar-light-theme($theme) {
    $accent: map-get($theme, accent);

    .skill-toolbar {
        background-color: mat-color($accent);
    }
}

@mixin app-toolbar-dark-theme($theme) {
    $primary: map-get($theme, primary);

    .skill-toolbar {
        background-color: mat-color($primary, 400);
    }
}

在我的styles.scss中:

@import "app/...../toolbar.component.scss-theme.scss";

@mixin custom-components-light-theme($theme) {
  @include app-toolbar-light-theme($theme);
}

@mixin custom-components-dark-theme($theme) {
  @include app-toolbar-dark-theme($theme);
}

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

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