I am an Angular beginner. Currently, I have a task to apply Dark Mode to an angular app. The body background color is successfully switching as expected (using angular-dark-mode npm - See Details: https://www.npmjs.com/package/angular-dark-mode)
In the npm doc, I think I can only apply the dark theme to global styles (i.e. body).
I tried the following in style.css already - but cannot see any style changes:
.p-card.dark-mode {
background-color: black;
}
.p-card.light-mode {
background-color: white;
}
Here is my code:
[dark-mode.component.html]
<p-toggleButton
[(ngModel)]="checked"
onLabel="Dark_Mode"
offLabel="Light_Mode"
(onChange)="onToggle()"
styleClass="darkMode_btn"
></p-toggleButton>
[dark-mode.component.ts]
import { Component, OnInit } from '@angular/core';
import { DarkModeService } from 'angular-dark-mode';
@Component({
selector: 'app-dark-mode',
templateUrl: './dark-mode.component.html',
styleUrls: ['./dark-mode.component.scss'],
})
export class DarkModeComponent {
darkMode$ = this.darkModeService.darkMode$;
checked: boolean = true;
constructor(private darkModeService: DarkModeService) {}
onToggle(): void {
this.darkModeService.toggle();
}
}
[style.css]
body.dark-mode {
height: auto;
min-height: 100% !important;
margin: 0;
background-color: #2d3436;
color: #dfe6e9;
}
body.light-mode {
height: auto;
min-height: 100% !important;
margin: 0;
background-color: white;
color: #2d3436;
}
.darkMode_btn {
height: 45px;
}
.p-card.dark-mode {
background-color: black;
}
.p-card.light-mode {
background-color: white;
}
So my question is simple. How can I apply the dark mode to in angular with a toggle button? Any idea, please?
------- Edited -------------------
I forgot to add one more thing. Here is how the structure of .HTML having the tags looks like:
<main>
<p-card styleClass="toolCard">
....
</p-card>
</main>
And I was able to see how other styles apply to the tag:
:host {
::ng-deep .toolCard.p-card {
border-radius: 1rem;
margin: 1em 0em;
background-color: var(--bluegray-50);
.p-card-body {
padding: 0.5rem;
}
}
}
I tried adding .dark-mode to the end of the .p-card-body. However, it did not make any difference. Still not working.. any ideas please?
CodePudding user response:
It appears you have nearly everything set up correctly. However, angular-dark-mode
only adds the light-mode
and dark-mode
classes to the body tag. It does not add the class to other tags.
Try setting the following in your style.css:
body.dark-mode p-card {
background-color: black;
}
body.light-mode p-card {
background-color: white;
}
CodePudding user response:
I found the solution:
[style.css]
body.dark-mode .toolCard.p-card {
.p-card-body {
background-color: black;
}
}
body.light-mode .toolCard.p-card {
.p-card-body {
background-color: white;
}
}