Angular button toggle to change body background using Hostbinding

103 views Asked by At

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;
1

There are 1 answers

0
Grogu On

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:

.bgnight{
    background-color: #000;
    color: #fff;
}

but:

:root { // putting in :root makes the variables available everywhere in the app
  .night {
    // define your color palette variable for dark theme
    --background-color: #000;
    --text-color: #fff;
  }
  .light {
    // define your color palette variable for light theme
    --background-color: #fff;
    --text-color: #000;
  }
}

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.

background-color: var(--background-color);
color: var(--text-color);

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