首页 > 解决方案 > 使用角度和材质将主题当前值存储在 localStorage

问题描述

我有一个带有 2 个选项(比如深色和浅色)的主题,效果非常好。但是我想要实现的是当我选择深色主题并且我想将该深色值存储在 localStorage 中时。我有一个带有 Material 主题的 Angular。请参阅下面的代码(这是主题按钮的来源):

模板代码:

<li>
    <label class="theme-option-check">
        <input type="radio" name="theme" value="light" [(ngModel)]="AppConfig.theme" />
        <span class="theme-option-item bg-color-page">
            <span class="overlay">
                <mat-icon>check</mat-icon>
            </span>
            <span>Regular</span>
        </span>
    </label>
</li>
<li>
    <label class="theme-option-check">
        <input type="radio" name="theme" value="dark" [(ngModel)]="AppConfig.theme" />
        <span class="theme-option-item bg-color-dark">
            <span class="overlay">
                <mat-icon>check</mat-icon>
            </span>
            <span>Dark</span>
        </span>
    </label>
</li>

除此之外,我还在 config.ts 文件中管理应用程序的配置。请参见下面的代码:

function makeAppConfig() {
  const date = new Date();
  const year = date.getFullYear();

  const AppConfig = {
    user: 'User',
    year,
    layoutBoxed: false,               // true, false
    navCollapsed: false,              // true, false
    navBehind: true,                 // true, false
    fixedHeader: true,                // true, false
    sidebarWidth: 'small',           // small, middle, large
    theme: 'light',                   // light, gray, dark
    colorOption: '32',                // 11,12,13,14,15,16; 21,22,23,24,25,26; 31,32,33,34,35,36
    AutoCloseMobileNav: true,         // true, false. Automatically close sidenav on route change (Mobile only)

    isLoadingResults: false
  };

  return AppConfig;
}

export const APPCONFIG = makeAppConfig();

在 app.component.ts 文件中,我添加了以下代码:

ngOnInit() {
    this.AppConfig = APPCONFIG;
    if (APPCONFIG.theme === 'light') {
      this.currentTheme = localStorage.getItem('light-theme');
    } else {
      this.currentTheme = localStorage.getItem('dark-theme');
    }
    console.log(this.currentTheme);
  }

这是我的模板文件:

<div id="app-main" class="app-main full-height"
   [ngClass]="{'fixed-header' : AppConfig.fixedHeader,
               'nav-collapsed' : AppConfig.navCollapsed,
               'nav-behind' : AppConfig.navBehind,
               'layout-boxed' : AppConfig.layoutBoxed,
               'theme-gray' : AppConfig.theme == 'gray',
               'theme-dark' : AppConfig.theme == 'dark',
               'sidebar-sm' : AppConfig.sidebarWidth == 'small',
               'sidebar-lg' : AppConfig.sidebarWidth == 'large'}">
  <router-outlet></router-outlet>
</div>

谁能帮助我如何将当前选定的值存储在浏览器存储中?

谢谢

标签: angularangular-material

解决方案


您也可以仅在项目上创建。 localStorage.setItem('selected-theme', 'light');// 默认值。每当您更改主题值时,请更新 localStorage 数据。


推荐阅读