Search code examples
angulartypescriptmaterial-designangular-material2

Angular Material 2. Switch theme from light to dark on click


So I have an Angular 2 Material application. And all I wanna do is just switch/toggle theme from dark to light by clicking simple button.

How can I do it ?


Solution

  • You can conditionally apply a CSS class to the document using the class binding syntax. This CSS class can then hold styling information for the application's dark theme.

    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;
        // Your code here
        
        changeTheme(): void {
            if (this.isDarkTheme) {
               this.isDarkTheme = false;
            } else {
               this.isDarkTheme = true;
            }
         }
    }
    

    You can then have the class specify the dark theme variant in your SCSS configuration:

    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);
    }