personal blog on code


Customize Angular Material Color

Sometimes the predefined colors primary, accent, and warn are not enough. We want to use a custom color, using the color attribute, without adding additional CSS classes.

<button mat-raised-button color="primary">Primary</button>
<button mat-raised-button color="accent">Accent</button>
<button mat-raised-button color="warn">Warn</button>

<!-- We want to use a custom color, without adding additional CSS classes: -->
<button mat-raised-button color="danger">Danger</button>
<button mat-raised-button color="success">Success</button>

Step 1

Create new file under src directory: theme.scss

Step 2

Creating a custom theme with the standard palettes for primary, accent and warn:

@use "@angular/material" as mat;

@include mat.core();

$app-primary: mat.define-palette(mat.$purple-palette);
$app-accent: mat.define-palette(mat.$teal-palette, A400);
$app-warn: mat.define-palette(mat.$orange-palette, 200);

$app-theme: mat.define-light-theme(
  (
    color: (
      primary: $app-primary,
      accent: $app-accent,
      warn: $app-warn
    )
  )
);

@include mat.all-component-themes($app-theme);

// to be continued in Step 3
// ...

Step 3

Create a palette for your custom color:

// extra Colors
$custom-success: mat.define-palette(mat.$teal-palette);
$custom-danger: mat.define-palette(mat.$red-palette);

.mat-success {
  background-color: mat.get-color-from-palette($custom-success, 500);
  color: mat.get-color-from-palette($custom-success, 500-contrast);
}

.mat-danger {
  background-color: mat.get-color-from-palette($custom-danger, 400);
  color: mat.get-color-from-palette($custom-danger, 400-contrast);
}

Result

picture of button with a danger color

All the best!

Github Source