Using Angular's Hostbinding feature to toggle a button and change the background color of the

How can I change the background color of a page and all child components when a toggle button is clicked? Can this be accomplished using HostBinding in Angular?

<div class="mainbody" [class.bgnight]="haveClass">
<button (click)="haveClass = !haveClass">Submit</button>

CSS

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

TS

   haveClass = false;

Answer №1

When incorporating a light/dark mode feature into your entire app, it's important to place the button and class condition around where your is located. The theme style should be defined in the style.css/style.scss file at the root of your app so that it can be accessed universally.

If you're not utilizing material themes, you'll need to define all variables yourself. Avoid hardcoding styles like this:

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

Instead, prefer using CSS variables within the :root selector to make them accessible throughout the app:

:root {
  .night {
    --background-color: #000;
    --text-color: #fff;
  }
  .light {
    --background-color: #fff;
    --text-color: #000;
  }
}

These theme variables can then be used to customize styles in the root and on other pages. All color-related properties should be defined as variables.

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

To enable users to switch between dark and light modes, you can set up a class condition like this:

  • [ngClass]="isNight ? 'night' : 'light'"

It's worth noting that using a toggle button for dark mode may reset the color settings upon page refresh or app reentry. To prevent this inconvenience, ensure that the chosen mode is cached for a seamless user experience.

In handling dark and light themes, CSS media queries such as

@media (prefers-color-scheme: light)
or
@media (prefers-color-scheme: dark)
are commonly employed. These queries ascertain the user's preferred theme based on their browser settings, eliminating the need for a toggle button. You can observe this functionality on the Google website https://www.google.com

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which CSS preprocessor is the best choice for WordPress: SASS or

After comparing SASS and LESS, I found that SASS is the clear winner in my opinion. Unfortunately, setting up SASS on my server requires ruby, gems, and other tools that I don't have access to. On the other hand, it seems like adding LESS to my proj ...

The progress bar seems to be malfunctioning

Need help with my progress bar, it's not working properly. Can someone assist me? var x = document.getElementById("p_bar"); for(var i = 0; i < 100; i++) { var wid; wid=1; if(wid == 800) break; else wid+=8; x.style.width=wid+" ...

how to change the class of a div when clicking on a <p> element

Check out this code snippet: <p class="faq" onclick="toggleVisibility('answer1');"> How can I restrict email sending on my website? </p> <div id="answer1" class="hide"><sometext></div> these are my CSS styles! ...

Setting a property with a generic type array: Tips and tricks

Currently, I am working on implementing a select component that can accept an array of any type. However, I am facing some challenges in defining the generic and where to specify it. My project involves using <script setup> with TypeScript. Here is ...

Arrange the menu items in a column layout based on a given condition

Can someone assist me with displaying the menu subitems? I have created a plunker. Take a look at it to understand what I need (open plunker in full screen) https://plnkr.co/edit/IMEJFPfl5kavKvnUYaRy?p=preview In the plunker above, there are two dropdown ...

Locating Items in an Array using Angular 5 and Forming a New Array with the Located Objects

Looking for a way to extract objects from an array that have the type "noActiveServiceDashboard" and "extraAmountDashboard". I want to create a new array with only these two entries in the same format. I've attempted using .find() or .filter() method ...

CSS absolute positioning not functioning as expected

I am experiencing an issue with positioning child elements within a parent element. The parent element is relatively positioned, while the two child elements are absolutely positioned to be in the top left and top right corners. However, despite having exp ...

The error message "Directive does not contain a property called 'element'.ts" is displayed

I'm encountering an issue where the property 'element' is not recognized on 'directive'. I am currently working on implementing functionalities for directives. import { Directive, ElementRef, HostListener } from '@angular/cor ...

Issues with the Diagonal HTML Map functionality

I'm seeking assistance to implement a unique Google Maps Map on my webpage. I have a particular vision in mind - a diagonal map (as pictured below). My initial approach was to create a div, skew it with CSS, place the map inside, and then skew the ma ...

What is the best way to utilize yarn in order to install a GitHub package that utilizes TypeScript and has not yet been compiled?

After making modifications to an npm package and using yarn link <project name> locally, everything works perfectly. However, when pushing it to GitHub and trying to add it to the project with yarn add <repo url>#<branch> instead of yarn ...

What is the correct way to customize colors for specific components in Material-ui?

Struggling with theming in Material-UI, particularly when it comes to customizing element colors. Some elements default to 'theme.palette.main.dark' and I want to override this behavior. For example, the TextField and SpeedDial components automa ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

Issue with Angular 10: Modal window fails to open upon second click

Encountering an issue with a Modal window overlapping the navigation bar and overlay due to a third-party bundle.js adding dynamic classes and divs under the parent-container. The problem arises from a fixed positioning of one of the classes which causes t ...

What causes the string to be treated as an object in React Native?

I am fetching a string value through an API and I need to display it in the View. However, the string value is coming as a Promise. How can I handle this? "Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65 ...

issue with uploading files in angular 7

Currently, I am facing an issue with Angular 7 where the input type "file" is not working as expected. However, in Angular 6, everything works fine. When submitting the input file type data in Angular 6, I receive a field list like this: https://i.sstat ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

The Angular Material Calendar is always designed to highlight the current date and keep focus on today's day

When I click on a date in the Angular Material Calendar, the tile for today's date is always highlighted. This occurs even if the selected date is in a different month. Do you think this behavior is a bug or a feature? I personally believe it is a fe ...

Switch the Follow/Following button depending on the user's current follow status with the individual

I am currently working on a functionality to toggle between the Follow and Following buttons based on whether the current user is following another individual. I have implemented an NgIF statement in my code, but I am facing challenges in properly checking ...

Typescript's interface for key-value pairing with generic types

Consider the example Object below: let obj1: Obj = { 'key1': { default: 'hello', fn: (val:string) => val }, 'key2': { default: 123, fn: (val:number) => val }, // this should throw an error, because the types of d ...

Building a custom dialog box using Angular Material with HTML and CSS

I've been exploring different approaches to create a customized angular material dialog with a unique header using CSS/SCSS and the TailwindCSS framework. I am aiming for a specific visual effect, similar to what is shown in the figure below. desired ...