Search code examples
angularangular-material

How to get mat-primary color in angular material-18


I have upgraded my Angular-16 project to angular-18. its working fine. Angular material-18 also upgraded.

Now I want to assign primary color to some elements, syntax is something like this:

@use '@angular/material' as mat;
background-color: mat.get-color-from-palette($primary, 300) !important;

But its not working. Need some help. I havent created any custom theme also.

Thanks


Solution

  • You can use mat.get-theme-color for this.

    Full Detailed Docs for get-theme-color

    background-color: mat.get-theme-color($theme, primary, 50) !important;
    

    We should also be aware of the number ranges for the hues, explained with examples below.

    When dealing with M3 Palette's you can refer to this doc reference. Here notice how the palette is within the range of 0-100

    $azure-palette: _apply-patches((
      0: #000000,
      10: #001b3f,
      20: #002f65,
      25: #003a7a,
      30: #00458f,
      35: #0050a5,
      40: #005cbb,
      50: #0074e9,
      60: #438fff,
      70: #7cabff,
      80: #abc7ff,
      90: #d7e3ff,
      95: #ecf0ff,
      98: #f9f9ff,
      99: #fdfbff,
      100: #ffffff,
    

    If you are dealing with a M2 Palette ($pink-palette) you can refer this doc reference. Notice how the numbers range from 50-A700

    $pink-palette: (
      50: #fce4ec,
      100: #f8bbd0,
      200: #f48fb1,
      300: #f06292,
      400: #ec407a,
      500: #e91e63,
      600: #d81b60,
      700: #c2185b,
      800: #ad1457,
      900: #880e4f,
      A100: #ff80ab,
      A200: #ff4081,
      A400: #f50057,
      A700: #c51162,
      contrast: (
        50: $dark-primary-text,
        100: $dark-primary-text,
        200: $dark-primary-text,
        300: $dark-primary-text,
        400: $dark-primary-text,
        500: $light-primary-text,
        600: $light-primary-text,
        700: $light-primary-text,
        800: $light-primary-text,
        900: $light-primary-text,
        A100: $dark-primary-text,
        A200: $light-primary-text,
        A400: $light-primary-text,
        A700: $light-primary-text,
      )
    );
    

    SCSS:

    @use '@angular/material' as mat;
    
    $theme: mat.define-theme(
      (
        color: (
          theme-type: light,
          primary: mat.$azure-palette,
          tertiary: mat.$blue-palette,
        ),
      )
    );
    
    body {
      background-color: mat.get-theme-color($theme, primary, 50) !important;
      @include mat.all-component-themes($theme);
      font-family: Roboto, 'Helvetica Neue', sans-serif;
      margin: 0;
      padding: 30px;
      height: 100%;
    }
    
    html {
      height: 100%;
    }
    
    @include mat.core();
    @include mat.color-variants-backwards-compatibility($theme);
    

    Stackblitz Demo