Create Angular Material Theme with CSS Variables

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);
    }
    }

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;
}

How to apply angular-material built in theme variables in component style?

Color variables are declared in scss files, while you are importing css. I.e. you cannot get sass variables via importing compiles css files.

If you want doing it properly you need to follow https://material.angular.io/guide/theming-your-components guidelines.

E.g. getting material colors:

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

$primary: mat-palette($mat-indigo);
$accent: mat-palette($mat-pink, A200, A100, A400);
$theme: mat-light-theme((
color: (
primary: $primary,
accent: $accent,
)
));

$color: mat-get-color-config($theme);

$primary: map-get($color, primary);

.candy-carousel {
// Use mat-color to extract individual colors from a palette.
background-color: mat-color($config); // color will be there
border-color: mat-color($config, A400); // a bit different hue
}

how to use angular material theme colour variables in other scss files

Your variable is a map. You have to declare which attribute you want.

background-color: map-get($weather-theme-primary, 100)


Related Topics



Leave a reply



Submit