Trying to set dark theme in Angular Material v15
@use '@angular/material' as mat;
@include mat.core();
@import 'bluegrey-palette';
$light-theme: mat.define-light-theme((
color: (
primary: $primary,
accent: $accent,
warn: $warn
)
));
$dark-theme: mat.define-dark-theme((
color: (
primary: $primary,
accent: $accent,
warn: $warn
),
// typography: mat.define-typography-config(),
// density: 0
));
@include mat.core-color($light-theme);
@include mat.button-color($light-theme);
//@include mat.all-component-themes($light-theme);
.darkMode {
@include mat.core-theme($dark-theme);
@include mat.button-theme($dark-theme);
@include mat.all-component-colors($dark-theme);
}
$primary: mat.define-palette(mat.$blue-grey-palette);
$accent: mat.define-palette(mat.$blue-grey-palette);
$warn: mat.define-palette(mat.$blue-grey-palette);
It works fine inside a mat-sidenav-container
, but inside another modules the background remains white and typography remains black.
I tryed this but is not working:
<body class="mat-app-background">
<app-root></app-root>
</body>
I made this based on documentation: https://material.angular.io/guide/theming#application-background-color
Adding your darkMode class selector to the body tag in index.html will get it to work immediately:
<body class="mat-app-background darkMode">
<app-root></app-root>
</body>
If you want to toggle dark and light mode, you will need to create a service and tie the toggleDarkTheme()
to a button somewhere:
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class StyleManager {
isDark = false;
static readonly darkStyleName = 'darkMode';
constructor() {}
public toggleDarkTheme() {
if (this.isDark) {
document.body.classList.remove(StyleManager.darkStyleName); // Remove darkMode
this.isDark = false;
} else {
document.body.classList.add(StyleManager.darkStyleName); // Add darkMode
this.isDark = true;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With