2017-03-07 43 views
0

我希望有人能夠幫助我,因爲我無法從邏輯上理解如何去做。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上得到一些幫助。

謝謝大家,非常感謝任何支持。

回答

0

在您的FooterComponent的ngOnInit中,您可以從localStorage讀取並根據該值設置主題(如果存在)。

東西線沿線的:

ngOnInit() { 
    let storedTheme = localStorage.getItem('theme'); 
    if (storedTheme) { 
    this.themes.setTheme(storedTheme); 
    } 
} 
+0

它的工作! @Snorkpete你是我的朋友!非常感謝你的回覆和完美的回答!我不知道該怎麼感謝你才足夠! –

+0

我現在確實有一個非常輕微的問題,因爲我選中了激活darkmode的方框,然後刷新頁面,即使darkmode仍然處於活動狀態,複選框默認回到'Unchecked',而不是顯示checked.I嘗試添加此: [選中] = 「TRUE」 在此結束: <輸入的ID = 「themeswitch」 類型= 「複選框」 名稱= 「設定主題」[(ngModel)] = 「currentTheme」(變化)=「checked(no,$ event)」[checked] =「true」/> 並玩過一些值來引用它,但沒有任何影響? 也試過這個: 文件。getElementById(「themeswitch」)。checked = true; –

+0

您在模板中將複選框綁定到currentTheme,因此您可能還想在ngoninit中設置currentTheme值。不幸的是,我不在PC附近,在手機上輸入代碼幾乎是不可能的 – snorkpete