Search code examples
angular

how to create custom palette with angular material?


I'm new user to angular material2 and i try to define custom theme for my app. So i want to define a palette for my custom theme:

@use "@angular/material" as mat;
@include mat.core();

$m2-custom-palette: (
  50: #e1f5fe,
  100: #b3e5fc,
  200: #81d4fa,
  300: #81d4fa,
  400: #29b6f6,
  500: #03a9f4,
  600: #039be5,
  700: #0288d1,
  800: #0277bd,
  900: #01579b,
  contrast: (
    50: #000,
    100: #000,
    200: #000,
    300: #fff,
    400: #fff,
    500: #fff,
    600: #fff,
    700: #fff,
    800: #fff,
    900: #fff,
  ),
);
$my-primary: mat.m2-define-palette(mat.$m2-light-blue, 500);

After i define $my-primary variable appears error: "Undefined variable mat.$m2-light-blue". I'm confused. Pls help.


Solution

  • The error happens because $m2-light-blue doesn't exist. Instead, you should define your custom color palette and use it directly. Here's a simplified fix:

    @use "@angular/material" as mat;
    
    //  Angular Material core here
    @include mat.core();
    
    // your custom palette here
    $m2-custom-palette: (
      50: #e1f5fe,
      100: #b3e5fc,
      200: #81d4fa,
      300: #81d4fa,
      400: #29b6f6,
      500: #03a9f4,
      600: #039be5,
      700: #0288d1,
      800: #0277bd,
      900: #01579b,
      contrast: (
        50: #000,
        100: #000,
        200: #000,
        300: #fff,
        400: #fff,
        500: #fff,
        600: #fff,
        700: #fff,
        800: #fff,
        900: #fff,
      ),
    );
    
    //   primary color 
    $my-primary: mat.define-palette($m2-custom-palette, 500);
    
    // put primary +accent +  warn palettes here
    $my-theme: mat.define-light-theme((
      color: (
        primary: $my-primary,
        accent: mat.define-palette(mat.$pink-palette),
        warn: mat.define-palette(mat.$red-palette),
      ),
    ));
    
    // Include  theme style here
    @include mat.all-component-themes($my-theme);

    This should resolve your issue. You're basically defining your custom colors and then applying them properly.