Angular 2主题切换器本地存储
我希望有人能帮我做这件事,因为我不知道该怎么做 我的Angular 2应用程序页脚中有一个复选框,选中该复选框时,该复选框会将我的应用程序切换到“暗模式”,并在复选框上调用“更改”事件,如my footercomponent.html文件中所示: footercomponent.htmlAngular 2主题切换器本地存储,angular,checkbox,local-storage,Angular,Checkbox,Local Storage,我希望有人能帮我做这件事,因为我不知道该怎么做 我的Angular 2应用程序页脚中有一个复选框,选中该复选框时,该复选框会将我的应用程序切换到“暗模式”,并在复选框上调用“更改”事件,如my footercomponent.html文件中所示: footercomponent.html <input id="themeswitch" type="checkbox" name="setting-theme" [(ngModel)]="currentTheme" (change)="chec
<input id="themeswitch" type="checkbox" name="setting-theme" [(ngModel)]="currentTheme" (change)="checked(no,$event)" />
我有一个主题“服务”设置,其中包含默认主题,还运行一个switch语句来选择所需的主题,并根据先前选中的复选框中的选择将其应用于应用程序
主题服务.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');
}
}
}
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的一点帮助
谢谢大家,非常感谢大家的支持。在您的ngOnInit for the footer组件中,您可以从localStorage读取内容,并根据该值设置主题(如果存在) 大致如下:
ngOnInit() {
let storedTheme = localStorage.getItem('theme');
if (storedTheme) {
this.themes.setTheme(storedTheme);
}
}
成功了@Snorkpete你是一个传奇,我的朋友!!非常感谢您对我的问题的友好回答和完美回答!我对你感激不尽!我现在确实有一个非常轻微的问题,因为我选中该框以激活darkmode,然后刷新页面,即使darkmode仍然处于活动状态,但复选框默认为“未选中”,而不是显示“已选中”。我尝试在结尾处添加以下内容:[checked]=“true”:并使用一些值来引用它,但什么都没有生效?还尝试了以下方法:document.getElementById(“themeswitch”).checked=true;您的模板中有一个到currentTheme的复选框绑定,因此您可能还希望在ngoninit中设置该currentTheme值。不幸的是,我离电脑不远,在手机上输入代码几乎是不可能的