Steps to customize the color scheme in your Angular application without relying on external libraries

Is there a way to dynamically change the color scheme of an Angular app by clicking a button, without relying on any additional UI libraries?

Here's what I'm trying to achieve - I have two files, dark.scss and light.scss, each containing variables like the example below but with different values.

:root{
    --body-bg:#fff;   
    --frn-bg-color:#fff;
    --input-border-color:#787878;
    //...
}

In the styles.scss file, these variables are called using @require './theme/dark.scss';. However, this setup is static and requires rebuilding the app to switch to @require './theme/light.scss';.

So my question is, how can I dynamically switch between theme files and apply a new color scheme without having to rebuild the entire app?

Answer №1

To enhance your CSS, consider using body.light and body.dark instead of :root as selectors for defining variables. With this approach, you can dynamically switch between light and dark themes using JavaScript by manipulating the document.body.classList.

For instance:

.light {
    --body-bg: #fff;   
    --frn-bg-color: #fff;
    --input-border-color: #787878;
    //...
}

and then in your script:

document.body.classList
  // Remove existing classes
  .remove('light', 'dark')
  // Add the desired theme
  .add('light');

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

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Utilizing ElementRef to create collapsible elements in Angular

Implementing basic collapse in Angular using ElementRef has proven to be a challenge for me, especially when dealing with HTML content within an ngFor loop. I need to pass the index value to the click event so it can retrieve the ID of the element. Check ...

The compilation process encountered an error: TypeError - Unable to access property 'exclude' as it is undefined (awesome-typescript-loader)

After successfully converting my existing Angular 2 project into Angular 4, I encountered the following error: Module build failed: TypeError: Cannot read property 'exclude' of undefined For more details, please refer to the attached image bel ...

Tips for embedding a script snippet into an Angular HTML file

Incorporating Bootstrap tooltip in a component using CLI and Bootstrap: Take note that Tooltips need to be initialized with jQuery: <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); </script> W ...

Rendering a sanitized string with interpolation in Angular 2

After receiving the string below: "Today's product of the day is {{product_code}} !" I took this string, sanitized it to bypass security restrictions using HTML this.DomSanitizer.bypassSecurityTrustHtml(str) and inserted it into my template using ...

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

Resolving parent routes in Angular 2

I am encountering an issue with my code. The 'new' route is a child route for the 'users' route. The 'users' route has a resolver, and everything works fine up to this point. However, after successfully creating a new user, ...

Angular: How can the dropdown arrow in 'ng-select' be eliminated?

Is there a way to hide the dropdown arrow in an 'ng-select' element in Angular? <div class="col-md-6"> <ng-select id="selectServiceType" [items]="clientServiceTypes$ | async" pl ...

Issues encountered when attempting to add a new user on Firebase

I am facing an issue with this function that is supposed to add new users to my firebase database, but for some reason, it's not working. exports.createUserWithEmailAndPassword = functions.https.onCall( async(data, context) => { const { ...

Encountering an issue with the constructor function type for @types/tapable/index

Everything was running smoothly on my production website until I decided to run the "npm install" command on the server, followed by the "npm run build:prod" command. Unfortunately, I encountered the following error: ERROR in [at-loader] node_modules/@typ ...

How to share data between two different components in Angular 6

I have a component called course-detail that fetches data (referred to as course) from my backend application. I want to pass this data to another component named course-play, which is not directly related to the course-detail component. The goal is to dis ...

Is there a way to disable tslint warnings for npm linked packages?

Currently, I am in the process of developing a set of Angular/TypeScript components within an application that utilizes this package. To facilitate the sharing of these components, I have utilized npm link. However, upon building the project, I encountered ...

Learning Angular2: What is the mechanism behind the automatic incrementation of the ID variable in this particular section?

In This specific part of the Angular2 Tutorial there is a feature that allows users to add new items to an array. Somehow, when the item is added, the ID is automatically incremented but the exact process behind this automation remains a mystery. I am awa ...

Navigate to a different page using the A-g Grid router when a row is

Having trouble making the router link interact with Ag grid. When I use the router link ="url", it always takes me to a different page every time I click on anything in the grid. What I really want is for clicking on an individual row to redirect me to an ...

What is the proper way to utilize variables in package.json with npm version 7.x.x?

I am looking to utilize npm scripts to access keys found in the directories section. "directories": { "client": "client", "server": "server" }, "scripts": { "test:client&qu ...

Unable to capture Metamask Errors

I am attempting to invoke a smart contract using ethers.contract and the signer from ethers.providers.web3Provider to leverage MetaMask. If the transaction fails, I want to capture the error and either retry or invoke a different function. However, my proj ...

Is there a way to determine the specific child property types of a custom Generic type extension?

I am looking to create a function that can retrieve a property from an extended generic type. Is this something achievable? Here is my attempt: interface Animal { readonly weight: {total: number} } interface Dog extends Animal { readonly weight: ...

Create a separate variable for every component within a custom module in Angular 4

In my Angular 5 project, I have a custom module called "Restaurant." The "Restaurant" module includes 5 components: Banner, Menu, Recommend, Basket, and Restaurantlayout. Restaurantlayout contains all the other components (Banner, Menu, Recommend, Basket ...

Creating a dynamic variable reference for ngModel in Angular 2 and above allows for flexible data binding

I am faced with a situation where I need to populate a table's headers based on the JSON data {id, name}. The ngModel name I have used in the component is this.id which needs to be mapped for custom filtering accordingly. For example, list=[{id:age ...

Switch between div elements in Angular 2 while dynamically changing their values depending on a specific condition for displaying or hiding

After referring to the solution found in (Hide/show individual items inside ngFor), I am facing a challenge regarding setting the value of pinMe[j] based on a condition. In my scenario, I need to toggle between div elements while also determining what shou ...