Issue
I wanted to create a dynamic background-color
for my .active
class of my mat-list-item
HTML:
<mat-list-item
*ngFor="let page of pages"
matRipple
routerLinkActive="active"
>
<a [routerLink]="page.path" (click)="drawer.close()"
><mat-icon class="mat-18">{{ page.iconName }}</mat-icon
>{{ page.name }}</a
>
</mat-list-item>
So now basically assigning .active {background: red}
works as expected. What I wanted to do is apply the built in theme
$primary
color value. I’m using Angular Material indigo-pink
theme so I’ve tried doing the following
@import "[email protected]/material/prebuilt-themes/indigo-pink.css";
.active {
background-color: $primary;
}
This throws error
ERROR in Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable.
╷
│ background-color: $primary;
│ ^^^^^^^^
╵
Anything that I missed?
Solution
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 '[email protected]/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
}