Change the Angular Material 2 theme from light to dark with a simple click

I'm working on an Angular 2 Material project and I want to be able to switch the theme from dark to light with a single click of a button. Can anyone help me figure out how to achieve this?

Any tips or advice would be greatly appreciated!

Answer №1

To conditionally add a CSS class to the document, you can utilize the class binding syntax in Angular. This CSS class is used to define styling for the dark theme of the application.

In your menu:

app.component.html:

<div [class.dark-theme]="isDarkTheme">
    <!--Your application content here-->
    <mat-menu #more="mdMenu">
        <!--Your content here-->
        <button mat-menu-item (click)="changeTheme()">
            Change Theme
        </button>
    </mat-menu>
</div>

app.component.ts:

// import statements here
import {Component} from '@angular/core';

export class AppComponent {
    // Initialize isDarkTheme to false
    isDarkTheme: boolean = false;

    changeTheme(): void {
        if (this.isDarkTheme) {
           this.isDarkTheme = false;
        } else {
           this.isDarkTheme = true;
        }
     }
}

You can then define the dark theme variant in your SCSS configuration file:

theme.scss:

@import '~@angular/material/core/theming/_all-theme';

@include mat-core();
.dark-theme {
    // Dark theme
    $app-dark-primary: mat-palette($mat-pink, 700);
    $app-dark-accent: mat-palette($mat-blue-grey);
    $app-dark-theme: mat-dark-theme($app-dark-primary, $app-dark-accent);

    @include angular-material-theme($app-dark-theme);
}

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

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

Automate the process of replacing imports in Jest automatically

Currently, I am in the process of setting up a testbench for a more intricate application. One challenge we are facing is that our app needs to call backend code which must be mocked to ensure the testbench runs efficiently. To address this issue, we utili ...

Only implement valueChanges on the second step of the form

I am utilizing the mat-stepper with a single form. My stepper has two steps only. I am looking to make an API request for every input value change, but only when the user is on the second step. How can I accomplish this? .ts ngOnInit() { this.formGr ...

Transforming a string into key-value pairs using Typescript

Is there a way to transform the given string into key-value pairs? TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false ...

Error retrieving the latest token in Angular before the component has fully loaded

I am seeking relevant advice to address my specific need: In my Angular application, I have implemented a jwt-based authentication system. After obtaining a new token and refresh token, I have set up a setTimeout function to ensure the token is refreshed ...

Modify a particular attribute in an array of objects

I am currently working on an Angular project and dealing with the following array object: { "DATA": [ { "CUSTOM1": [ { "value": "Item1", ...

This component is not compatible with JSX syntax and cannot be used as a JSX component. The type '() => Element' is not suitable for JSX element rendering

My Nextjs seems to be malfunctioning as I encountered the following error in a Parent component. Interestingly, the Spinner Component remains error-free Spinner.tsx export default function Spinner() { return ( <div className='flex ...

Closing iframe in Angular 4 after redirection

I am currently working on an Angular 4 application that involves integrating a third-party payment system called Tranzila. Tranzila offers a convenient integration method using an iframe, allowing users to make payments on their domain without me having to ...

Encountered Error: Unable to locate the module 'url' within webpack version 5 and Angular version 14

Encountering an error while working on a project in Angular 14 with [deepstream.io-client-js][1] installed. See the issue below. [1]: https://www.npmjs.com/package/deepstream.io-client-js A notable change has occurred: webpack < 5 previously included ...

Declaration of React conditional props in TypeScript

I am facing an issue with my React component where the type is determined by a runtime variable (isMock). I am struggling to get the TS declarations to function properly: The component can either be MockedProvider or ApolloProvider from @apollo/client, ea ...

Unable to leverage vscode workspace path for the next js 13 project

I am facing an issue with TypeScript despite having the latest versions installed in my project (TypeScript 5.2.2 and @types/react 18.2.21): Next 13 — client and async server component combined: 'Promise<Element>' is not a valid JSX elem ...

Encountering a Runtime Exception while setting up a Client Component in the latest version of Next JS (v13.3

I am facing an issue with a component in my Next JS website. When I attempt to convert it into a Client Component, the page fails to load in the browser and I encounter the following unhandled runtime exception: SyntaxError: "undefined" is not va ...

Discover the unique value in Angular if it is not present in the list

I have a question about handling values in a list and displaying the "create value" component to the user when needed. How can I efficiently compare search input values with those in the list and determine if a match exists? If no match is found, the "cr ...

Angular - Verify the presence of queryParams on the root path (/)

I have a legacy application built in Vaadin that requires migration to Angular 15 while maintaining the same URL structure. The transition is nearly complete, with one crucial task remaining: identifying if there are no URL query parameters present on the ...

Issue: Map container not located when implementing a leaflet map with Angular

Here is the complete error message: core.js:6479 ERROR Error: Map container not found. at NewClass._initContainer (leaflet-src.js:4066) at NewClass.initialize (leaflet-src.js:3099) at new NewClass (leaflet-src.js:296) at Object.createMap [a ...

Angular Proxy is not passing the WebSocket Upgrade Header

When using the Angular CLI proxy by running ng serve --proxy-config proxy.conf.json the configuration looks like this: { "/api/*": { "ws": true, "secure": false, "target": "http://localhost:80", "logLevel": "debug" ...

Issue: The function "generateActiveToken" is not recognized as a function

I encountered an issue in my Node.js project and I'm unsure about the root cause of this error. Within the config folder, there is a file named generateToken.js which contains the following code snippet: const jwt = require('jsonwebtoken'); ...

"Error: The update depth has exceeded the limit while trying to use the

I've been working on implementing localStorage in NextJs using TypeScript by following this guide at , but I am encountering an error. https://i.sstatic.net/NX78a.png Specifically, the error occurs on the context provider repeatedly. Below is the c ...

GitHub Actions causing build failure in Angular project exclusively

I've encountered an issue where the GitHub Action workflow fails to compile an Angular project, even though it works fine on my local machine and that of my colleagues. It's worth noting that I'm using npm ci instead of npm install. The err ...

Inject a new observable into the current Subject

Having an Angular Subject named event$, I want to attach DOM controls as emitters to this observable when screens are loaded. The observable already has subscribers, so I am using a method to merge another observable with it, as shown below (Subscription m ...