Angular Material 18: как изменить цвет фона?

Я думаю, что это очень распространенная проблема, хотя мне не удалось найти решение.

У меня есть темная и светлая темы, такие как:

styles.scss

@use "@angular/material" as mat;

// Include the common styles for Angular Material.
@include mat.core();

// Define the theme object.
$light-theme: mat.define-theme(
  (
    color: (
      theme-type: light,
      primary: mat.$azure-palette,
      tertiary: mat.$blue-palette,
    ),
    density: (
      scale: -5,
    ),
  )
);

$dark-theme: mat.define-theme(
  (
    color: (
      theme-type: dark,
      primary: mat.$azure-palette,
      tertiary: mat.$blue-palette,
    ),
    density: (
      scale: -5,
    ),
  )
);

// Include theme styles for core and each component used in your app.
html,
body {
  @include mat.all-component-themes($light-theme);

  .dark-theme {
    // This mixin only generates the color styles now.
    @include mat.all-component-colors($dark-theme);
  }

  height: 100%;
}

body {
  margin: 0;
  font-family: Roboto, "Helvetica Neue", sans-serif;
}

как изменить цвет фона компонентов Angular Material: один цвет для светлой и один цвет для темной темы? (по умолчанию он простой черный для светлой темы и простой белый для темной темы)

🤔 А знаете ли вы, что...
Фреймворк Angular имеет большое количество сторонних библиотек и расширений для расширения функциональности.


1
51
2

Ответы:

Определите цвета фона в своих темах

    $light-theme: mat.define-light-theme((
  color: (
    primary: mat.$azure-palette,
    tertiary: mat.$blue-palette,
    background: (
      background: mat.$white,
      status-bar: mat.$grey-200,
      app-bar: mat.$white,
      hover: rgba(mat.$black, 0.04),
      card: mat.$white,
      dialog: mat.$white,
      disabled-button: rgba(mat.$black, 0.12),
      raised-button: mat.$white,
      focused-button: rgba(mat.$black, 0.12),
      selected-button: mat.$grey-300,
      selected-disabled-button: mat.$grey-400,
      disabled-button-toggle: mat.$grey-200,
      unselected-chip: rgba(mat.$black, 0.12),
      disabled-list-option: rgba(mat.$black, 0.12),
    ),
  ),
  density: -2,
));

$dark-theme: mat.define-dark-theme((
  color: (
    primary: mat.$azure-palette,
    tertiary: mat.$blue-palette,
    background: (
      background: mat.$dark-grey,
      status-bar: mat.$grey-800,
      app-bar: mat.$grey-900,
      hover: rgba(mat.$white, 0.04),
      card: mat.$grey-800,
      dialog: mat.$grey-900,
      disabled-button: rgba(mat.$white, 0.12),
      raised-button: mat.$grey-800,
      focused-button: rgba(mat.$white, 0.12),
      selected-button: mat.$grey-700,
      selected-disabled-button: mat.$grey-600,
      disabled-button-toggle: mat.$grey-800,
      unselected-chip: rgba(mat.$white, 0.12),
      disabled-list-option: rgba(mat.$white, 0.12),
    ),
  ),
  density: -2,
));

Применение цветов фона на основе активной темы

html, body {
  background-color: mat.get-color-from-palette($light-theme-background, background);
  margin: 0;
  height: 100%;
  font-family: Roboto, "Helvetica Neue", sans-serif;
}

.dark-theme {
  background-color: mat.get-color-from-palette($dark-theme-background, background);
}

Добавить функцию для переключения темы

    toggleTheme(isDarkTheme: boolean) {

    document.body.classList.toggle('dark-theme', isDarkTheme);
  }

Решено

Добавьте класс mat-app-background к элементу <body> в index.html (см. документацию ):

<body class = "mat-app-background">
  <!-- content -->
</body>

При этом будут применены цвета фона по умолчанию #fafafa в светлой теме и #303030 в темной теме. Если вы хотите переопределить эти цвета, вы можете установить новое значение для переменной --mat-app-background-color в вашем styles.scss:

body {
  --mat-app-background-color: #eee;
  
  .dark-theme {
    --mat-app-background-color: #111;
  }
}

Чтобы переопределить цвета фона компонентов, вы можете установить значения для соответствующих переменных CSS:

body {
  --mdc-outlined-card-outline-color: #eee;
  --mat-table-background-color: #eee;
  // this is not a complete list, add more variables as needed
}

Я настоятельно советую не использовать всегда один и тот же цвет фона для всех компонентов Material: они намеренно имеют разные цвета фона, чтобы визуально разделить их.