Angular Material - Global Color Variables

How to use external stylesheet for Angular material colors

It turns out my issue was Angular was using node sass instead of dart sass, and since @use isn't a thing in node-sass, it threw an error. I had to delete the node-sass folder in my global dependencies.

Angular 9 / Material - Reuse of material theme variables in angular components style

You can do this in a different way:

There are something called 'partials'. You can create partials for various things and include/import them in your component.scss file and use them

Example:

At your root level, create a folder called styles. Inside styles, you can create multiple partials, one for variables, one for mixins, one for fonts etc.,

Partials start with an underscore for their file name such as _variables.scss, _mixins.scss, etc. The underscore will prevent the angular compiler from compiling everytime.

In '_variables.scss' file, you can create multiple global variables for colors, such as 

$primary-color: #fff;
$secondary-color: #333; etc

In '_mixins.scss' you can create mixins such as
@mixin mixin-name() {
mixins functionality
}

In your component.scss file, simply import them and use it.

component.scss

@import '../styles/mixins';
@import '../styles/variables';

.component-class-name {
background-color: $primary-color;
color: $secondary-color;
}

Create angular material theme with CSS variables

I created a little library to make this a little easier.

You can use it like so:

  1. Install:

    npm i angular-material-css-vars -S
  2. Then remove any existing @import '~@angular/material/theming'; from your main stylesheet file.

  3. Add this to your main stylesheet instead:

    @import '~angular-material-css-vars/main';
    @include initMaterialCssVars();
  4. Change the main theme color like so:

    import {MaterialCssVarsService} from 'angular-material-css-vars';

    export class SomeComponentOrService {
    constructor(public materialCssVarsService: MaterialCssVarsService) {
    const hex = '#3f51b5';
    this.materialCssVarsService.changePrimaryColor(hex);
    }
    }

Using Material variables from main styles.scss

Use the mat-color SASS mixin from Angular Material.

Here's some example usage:

@import '~@angular/material/theming';
@import 'app-theme.scss';

.extend-toolbar {
background-color: mat-color($candy-app-primary);
color: white;
}

For more info, check out the docs.



Related Topics



Leave a reply



Submit