Skip to content

Instantly share code, notes, and snippets.

@Fasteroid
Created May 22, 2024 18:48
Show Gist options
  • Save Fasteroid/47180d3c32a5794e473b70890c1f8b5c to your computer and use it in GitHub Desktop.
Save Fasteroid/47180d3c32a5794e473b70890c1f8b5c to your computer and use it in GitHub Desktop.
Ever wondered how to expose your entire Angular Material theme as normal CSS variables?
@use 'sass:map';
@use '@angular/material' as mat;
@include mat.core();
$my-app-primary: mat.define-palette(mat.$indigo-palette);
$my-app-accent: mat.define-palette(mat.$pink-palette);
$my-app-warn: mat.define-palette(mat.$amber-palette);
$my-app-theme: mat.define-light-theme(
(
color: (
primary: $my-app-primary,
accent: $my-app-accent,
warn: $my-app-warn,
),
)
);
@include mat.all-component-themes($my-app-theme);
:root {
@each $palkey, $palval in map-get($my-app-theme, color) { // iterate [primary, accent, warn...] seen above
@if type-of($palval) == "map" { // is this a color palette?
@each $colkey, $colval in $palval { // iterate shades (probably) of the palette
@if type-of($colval) == "color" { // is it really a color?
--#{$palkey}-#{$colkey}: #{$colval}; // expose it
}
}
}
}
}
@Fasteroid
Copy link
Author

All you really need to ensure is that $my-app-theme is defined for this example—so long as that's true you can just copy-paste the :root section into your global scss file and it should work.

Made this because I don't know what the fuck a mixin is (or how to use one), and it seems like a really bad idea to rely on a hardcoded path to where the theme is for my custom components.

Now if I ever borrow a component from another project, so long as it has this exposer in it (which is trivial to add), everything will just work.
😎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment