0

I'm trying to toggle between two custom themes. However, only some items on my page are switching on the toggle click. How do I make the other elements switch as well, such as borders, text, and hover colors?

Index.html

<body class="DefaultTheme">
  <app-root></app-root>
</body>

app.component.html

<div>
    <mat-slide-toggle name="toggle" (click)="changeTheme()">Change theme</mat-slide-toggle>
  </div>

app.component.ts

export class AppComponent{

  changeTheme() {
    if (document.body.classList.contains("DefaultTheme")) {
      document.body.classList.remove("DefaultTheme");
      document.body.classList.add("CustomTheme");
    }
    else {
      document.body.classList.remove("CustomTheme");
      document.body.classList.add("DefaultTheme");
    }
  }
}

theme.scss

@import '~@angular/material/theming';
@include mat-core();



$app-primary: mat-palette($mtb-pallete, 500);
$app-accent: mat-palette($mtb-pallete, 550);
$app-warn: mat-palette($mat-red);

$app-theme: mat-light-theme($app-primary,$app-accent,$app-warn);

$primary: mat-color($app-primary);
$accent: mat-color($app-accent);

.DefaultTheme {
@include angular-material-theme($app-theme);
}



$alt-primary: mat-palette($mtb-pallete, 590);
$alt-accent: mat-palette($mtb-pallete, 580);
$alt-warn: mat-palette($mat-red);

$alt-theme: mat-light-theme($alt-primary, $alt-accent, $alt-warn);

$primary: mat-color($alt-primary);
$accent: mat-color($alt-accent);

 .CustomTheme {
    @include angular-material-theme($alt-theme);
  }
BDev14
  • 9
  • 7
  • I am trying to use a slide toggle to switch between two different themes in my angular app. The primary and accent colors are all referred in the components' scss files. How do I tell the system which primary and which accent reference to use depending on the different themes when switching it using the slide toggle? I tried to put the $primary and $accent in the theme {} but that did not work and was unable to locate the references from the scss files. – BDev14 Oct 28 '19 at 15:41

1 Answers1

0

P.S this is more of a suggestion. I use a simple approach, may help in your case. I'll write two separate styles nested with a separate parent class name. and i'll change the parent class name based on the condition, which will eventually apply the different style to the whole page.

eg:

HTML file:

<div [ngClass]="(theme)?'pink-theme':'yellow-theme'">
  <h1 class="title">Hello World</h1>
  <p class="body">This is a demo</p>
</div>  

Styles:

.pink-theme {
  h1, p{
    background: pink;
    color: red;
}

.yellow-theme {
  h1, p{
    background: yellow;
    color: red;
}

Here when the theme is true pink-theme is applied and when it's false, yellow theme is applied. It's the most simplest way of style switching. Here is a working demo

Update 1:

Instead of adding and removing the class in component file, you can use [ngClass]

Community
  • 1
  • 1
Ranjith Varatharajan
  • 1,596
  • 1
  • 33
  • 76