Angular Material 2. 单击时将主题从浅色切换为深色 [英] Angular Material 2. Switch theme from light to dark on click

查看:18
本文介绍了Angular Material 2. 单击时将主题从浅色切换为深色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 Angular 2 Material 应用程序.我想要做的只是通过单击简单的 button 将主题从暗切换/切换到亮.

我该怎么做?

解决方案

在你的菜单中:

app.component.html:

<!--您的申请内容在这里--><md-menu #more="mdMenu"><!--您的内容--><button md-menu-item (click)="changeTheme()">改变主题</md-菜单>

app.component.ts:

//此处导入语句从 '@angular/core' 导入 {Component};导出类 AppComponent {//将 isDarkTheme 初始化为 falseisDarkTheme: boolean = false;//你的代码在这里更改主题():无效{如果(this.isDarkTheme){this.isDarkTheme = false;} 别的 {this.isDarkTheme = true;}}}

theme.scss:

@import '~@angular/material/core/theming/_all-theme';@include mat-core();.dark 主题 {//深色主题$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);

}

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 ?

解决方案

In your menu:

app.component.html:

<div [class.dark-theme]="isDarkTheme">
    <!--Your application content here-->
    <md-menu #more="mdMenu">
        <!--Your content here-->
        <button md-menu-item (click)="changeTheme()">
            Change Theme
        </button>
    </md-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;
        }
     }
}

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

}

这篇关于Angular Material 2. 单击时将主题从浅色切换为深色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆