Angular Material - Global color variables

前端 未结 3 1067
温柔的废话
温柔的废话 2020-12-30 07:01

Looking at the Angular Material documentation, they recommend using a -theme file per component to manage applying any theme-related styles to a specific class.

3条回答
  •  孤城傲影
    2020-12-30 07:28

    I have defined primary,accent and warn colors as css custom variables in the styles.css file like so:

    @import "~@angular/material/theming";
    @include mat-core();
    
    $my-primary: mat-palette($mat-blue-grey);
    $my-accent: mat-palette($mat-amber, A200, A100, A400);
    $my-warn: mat-palette($mat-deep-orange);
    
    $my-2-primary: mat-palette($mat-pink, 400, 200, 600);
    $my-2-accent: mat-palette($mat-blue, A200, A100, A400);
    $my-2-warn: mat-palette($mat-deep-orange, 500, 300, 700);
    
    .dark-theme {
      $my-theme-dark: mat-dark-theme($my-primary, $my-accent, $my-warn);
      @include angular-material-theme($my-theme-dark);
      $primary: mat-color($my-primary);
      $accent: mat-color($my-accent);
      $warn: mat-color($my-warn);
      $fg_palette:map-get($my-theme-dark, foreground);
      $bg_palette:map-get($my-theme-dark, background);
      $fg:map-get($fg_palette, text);
      $bg:map-get($bg_palette, background);
    
      --primary: #{$primary};
      --accent: #{$accent};
      --warn: #{$warn};
      --fg: #{$fg};
      --bg: #{$bg};
    }
    
    .dark-theme-2 {
      $my-2-theme-dark: mat-dark-theme($my-2-primary, $my-2-accent, $my-2-warn);
      @include angular-material-theme($my-2-theme-dark);
      $primary: mat-color($my-2-primary);
      $accent: mat-color($my-2-accent);
      $warn: mat-color($my-2-warn);
      $fg_palette:map-get($my-2-theme-dark, foreground);
      $bg_palette:map-get($my-2-theme-dark, background);
      $fg:map-get($fg_palette, text);
      $bg:map-get($bg_palette, background);
    
      --primary: #{$primary};
      --accent: #{$accent};
      --warn: #{$warn};
      --fg: #{$fg};
      --bg: #{$bg};
    }
    

    And used these variables in any of my components like so:( in my-custom-component.scss)

    .some-class {
        color: var(--primary)
    }
    
    .another-class {
        background-color: var(--bg)
    }
    
    .yet-another-class {
        border-color: var(--accent)
    }
    

    By doing like this, i can change any value related to color in any component, because these variables are global (defined in styles.css) As i change theme, these colors also change according to new theme's color

提交回复
热议问题