Angular Material comes with pre-built themes to make getting started easy. Once you’ve picked a theme such as indigo-pink, you may want to re-use the base colours in your own components for consistency.

Instead of creating your own scss variables, I would suggest copying base colours from Angular Material.

Let’s copy $primary and $accent colours from Angular Material:

@import "~@angular/material/theming";

// Copy colour palettes individually
$app-primary: mat-palette($mat-indigo);
$app-accent: mat-palette($mat-pink);

// Create variables to use in project
$primary: mat-color($app-primary);
$accent: mat-color($app-accent);Code language: SCSS (scss)

Assuming you’re working on a real project and not a hello-world app, you should consider creating a file to keep these variables.

src/assets/_variables.scssCode language: Bash (bash)

As this is a new file, Angular compiler needs to know about it.

Go ahead and add it to the styles array in your angular.json:

"styles": [ 
    "src/assets/_variables.scss"
]
Code language: JSON / JSON with Comments (json)

Finally, you can import the new variables file in any component and use $primary and $accent:

@import "./../../../assets/_variables";

.entry {
    background-color: $primary;
}Code language: CSS (css)

So there you have it! This is how I re-use colours from Angular Material to keep things consistent.

Do you know any other way to do this? Let me know in the comments below!

Umut Esen

Software Engineer specialising in full-stack web application development.

Leave a Reply