Reputation: 344
I've got 2 custom themes for my app which i can switch during runtime already. So they define in a theme.scss file, the colors for primary, accent and warn. So i can use these theme-colors on the standard material-components which takes such a color input in the HTML.
My question now is, how can i make use of these colors in the .scss files of my custom components? For example my font-color or background-color should change by changing the theme?
This is my theme.scss file in the moment:
@import "~@angular/material/theming";
@include mat-core();
$primary: mat-palette($mat-yellow);
$accent: mat-palette($mat-pink);
$warn: mat-palette($mat-red);
$light-theme: mat-light-theme(
$primary,
$accent,
$warn
);
@include angular-material-theme($light-theme);
$dark-primary: mat-palette($mat-blue);
$dark-accent: mat-palette($mat-green);
$dark-warn: mat-palette($mat-orange);
$dark-theme: mat-dark-theme(
$dark-primary,
$dark-accent,
$dark-warn
);
.dark-theme {
color: $light-primary-text;
@include angular-material-theme($dark-theme);
}
The css-class .dark-theme gets layed upon the app-component during runtime, to switch the theme.
But how can i now do something like:
MyComponent.scss
:host {
background-color: primary;
}
Would really appreciate any help on this, thank you! :)
Upvotes: 1
Views: 675
Reputation: 797
i created a new file theme.service.ts. in this file i define my theme keys, as well as hold my functions to switch out the theme. here you would also add more themes and their switching functions
export const redTheme= {
primary: '#f00',
primaryDark: '#aa0000',
secondary: '#fff',
background: '#000'
};
@Injectable({
providedIn: 'root'
})
export class ThemeService {
toggleRed() {
this.setTheme(redTheme);
}
setTheme(theme: {}) {
Object.keys(theme).forEach(k =>
document.documentElement.style.setProperty(`--${k}`, theme[k])
);
}
}
now in your main styles.scss you add the keys which will be switched out at the top of your file. make sure you have the same key names.
// styles.scss
@import './app/utils/material/material-custom-theme';
@import '~@angular/material/theming';
@include angular-material-typography($custom-typography);
:root {
// default theme
--primary: #00f;
--primaryDark: #0000bb;
--secondary: #0f0;
--background: #000;
}
after this you can import theme.service into your component where you switch your theme (i do it in my sidenavcomponent upon button click). In order to use this themes colors on your custom components you need to use the variable names of the keys for the color which you would like to use. for example like this
// example.component.scss
.example-custom-class {
background: var(--primary);
color: var(--secondary);
box-shadow: 10px var(--primaryDark);
}
this is how i handled theme switching in my application. it is bypassing the material theming a bit but with this you can set theme colours on your custom components. hope i was able to help! :)
Upvotes: 1