I have a page with a toggle button, which I need to change background colour of the page and all child components as well. How can I acheive this? Is it possible to do using HostBinding, if yes, how? Html
<div class="mainbody" [class.bgnight]="haveClass">
<button (click)="haveClass = !haveClass">Submit</button>
CSS
.bgnight{
background-color: #000;
color: #fff;
}
TS
haveClass = false;
As you are installing light/dark mode for your whole app, you should put the button and the class condition around where your is. Your theme style must be in style.css/style.scss file at the root of you app, to be available everywhere.
As you are not using material themes, you have to variabilize everything yourself. You should not do:
but:
and then in your other styles in the root and in style pages, you can use these theme variables to customize. Everything linked to the colors must be variabilized.
You can keep class condition and switch between dark and light mode:
[ngClass]="isNight ? 'night' : 'light'"
Note that handling dark mode with a toggle button will reinitialize the color each time you refresh the page or when you leave and come back on the app. So you need to cache chosen mode, otherwise it's gonna be bothersome for your users.
What is normally used to handle dark and light theme are css media queries
@media (prefers-color-scheme: light)
or@media (prefers-color-scheme: dark)
. They determine which theme the user wants as it's a browser parameter. All that without toggle button. You can try in on google website https://www.google.com