angular - 使用角度和材质将主题当前值存储在 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>
谁能帮助我如何将当前选定的值存储在浏览器存储中?
谢谢
解决方案
您也可以仅在项目上创建。
localStorage.setItem('selected-theme', 'light');
// 默认值。每当您更改主题值时,请更新 localStorage 数据。
推荐阅读
- android - 使用 react-native-maps 组件打开屏幕时 Expo 独立应用程序崩溃
- php - 如何在woocommerce商店的主页上获取产品ID?
- android - 关闭时的软键盘强制片段更改
- python - TypeError:读取json时字符串索引必须是整数
- regex - Dart Regex:只允许点和数字
- c# - 在网格上生成随机孔的算法
- python - 如何编辑 Python 路径 - 我想我在安装 Visual Studio 后不小心更改了它
- spring-boot - 如何在我的项目中强制提交消息?
- extjs - 检查使用类检索到的组件上的 isExpaned()
- reactjs - ReactJS 将悬停更改为 onclick