简体   繁体   中英

How to change color based on Dark or Light Theme - Angular Material

In my app I have a light theme and a dark theme. I'm trying to style a custom component, so that a color will depend on whether it's a dark theme or light theme. This is my code in the custom component 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'
    }
}

Is there a way to change the background of the toolbar based on whether I'm in a dark or light theme?

Use prefers-color-scheme media query:

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

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

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

I found how to do this. I create two mixin component themes, and add the light one to the light theme, and the dark to the dark theme.

@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);
    }
}

And in my 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM