Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material v15 Dark/Light Theme

Trying to set dark theme in Angular Material v15

  • theme.scss:

@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);
}
  • _bluegrey-palette.scss:

$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:

  • index.html:
    <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

like image 914
sonEtLumiere Avatar asked Sep 19 '25 08:09

sonEtLumiere


1 Answers

Static Dark Theme

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>

Dynamic dark Theme

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;
    }
  }
}
like image 189
clayton Avatar answered Sep 22 '25 02:09

clayton