Angular 2 Theme Switcher本地存储
问题描述:
我希望有人能够帮助我,因为我无法从逻辑上理解如何去做。Angular 2 Theme Switcher本地存储
我有我的角2的应用程序页脚,其中我的应用程序切换到选中时,“暗模式”复选框,呼吁像这样的复选框“更改”事件在我footercomponent.html文件:
footercomponent.html
此引用“检查”在我footercomponent.ts文件功能,它运行一个if语句设置一个主题,以主题B的主题(主题光)(黑暗的主题)。然后,它还将值A或B添加到名为theme:A或theme:B的键值对下的本地存储中,具体取决于是否选中该复选框。主题变化是所有工作都很好,但知道如何回忆本地存储的价值并将它应用到某个地方令我感到困惑。
footercomponent.ts
export class FooterComponent implements OnInit {
constructor(public settings: SettingsService, public themes: ThemesService,) {
}
ngOnInit() {
}
// Theme Switch
checked(value,event){
if(event.target.checked){
this.themes.setTheme('B');
//Add Theme value to local storage
localStorage.setItem('theme', 'B');
// document.getElementById("myCheck").checked = true;
}
else if (!event.target.checked){
this.themes.setTheme('A');
//Add Theme value to local storage
localStorage.setItem('theme', 'A');
}
}
}
我有一个主题“服务”的设置,其中包含了默认的主题,他也有一个switch语句来选择所需的主题,并根据从选择将其应用到应用程序先前选中的复选框。
theme.service.ts
const themeA = require('../../shared/styles/themes/theme-a.scss');
const themeB = require('../../shared/styles/themes/theme-b.scss');
@Injectable()
export class ThemesService {
styleTag: any;
defaultTheme: string = 'A';
constructor() {
this.createStyle();
this.setTheme(this.defaultTheme);
}
private createStyle() {
const head = document.head || document.getElementsByTagName('head')[0];
this.styleTag = document.createElement('style');
this.styleTag.type = 'text/css';
this.styleTag.id = 'appthemes';
head.appendChild(this.styleTag);
}
setTheme(name) {
switch (name) {
case 'A':
this.injectStylesheet(themeA);
break;
case 'B':
this.injectStylesheet(themeB);
break;
}
}
injectStylesheet(css) {
this.styleTag.innerHTML = css;
}
getDefaultTheme() {
return this.defaultTheme;
}
}
我可以在本地存储设置面板,因为我选中或清除该复选框中的值更新浏览器中看到,所以这部分工作正常,我只是不知道在哪里或如何调用或引用我的代码中的本地存储的值,以便将该值应用于用户复选框选择(如果有意义的话)?
因此,当用户选中该框时,它会应用黑暗的主题,当他们刷新浏览器时,仍然会选择深色主题。我明白它的一个角度应用程序,他们甚至可能不会刷新页面,因为所有的功能都是动态加载的,但只要我愿意解决这个问题,希望可以从SO上得到一些帮助。
谢谢大家,非常感谢任何支持。
答
在您的FooterComponent的ngOnInit中,您可以从localStorage读取并根据该值设置主题(如果存在)。
东西线沿线的:
ngOnInit() {
let storedTheme = localStorage.getItem('theme');
if (storedTheme) {
this.themes.setTheme(storedTheme);
}
}
它的工作! @Snorkpete你是我的朋友!非常感谢你的回复和完美的回答!我不知道该怎么感谢你才足够! –
我现在确实有一个非常轻微的问题,因为我选中了激活darkmode的方框,然后刷新页面,即使darkmode仍然处于活动状态,复选框默认回到'Unchecked',而不是显示checked.I尝试添加此: [选中] = “TRUE” 在此结束: 并玩过一些值来引用它,但没有任何影响? 也试过这个: 文件。getElementById(“themeswitch”)。checked = true; –
您在模板中将复选框绑定到currentTheme,因此您可能还想在ngoninit中设置currentTheme值。不幸的是,我不在PC附近,在手机上输入代码几乎是不可能的 – snorkpete