1

i created a method that change the theme of my app.

I tried to pass a theme variable to localstorage but without success, no effects.

I'd like to save the result of condition in local storage, so if i change route i can see the same theme setted before.

  @HostBinding('class.light-theme') lightTheme: boolean = false;
  @HostBinding('class.dark-theme') darkTheme: boolean = true;
  theme: string = 'Dark';

  toggleTheme(): void {

    if (this.theme === 'Light') {
      this.lightTheme = false;
      this.darkTheme = true;
      this.theme = 'Dark';
    } else {
      this.darkTheme = false;
      this.lightTheme = true;
      this.theme = 'Light';
    }
  }
}
mantegnous
  • 53
  • 1
  • 9

3 Answers3

1

This should work:

  theme: string = localStorage.getItem('theme');
  @HostBinding('class.light-theme') lightTheme: boolean = this.theme === 'Light';
  @HostBinding('class.dark-theme') darkTheme: boolean = this.theme === 'Dark';

  toggleTheme(): void {

    if (this.theme === 'Light') {
      this.lightTheme = false;
      this.darkTheme = true;
      this.theme = 'Dark';
    } else {
      this.darkTheme = false;
      this.lightTheme = true;
      this.theme = 'Light';
    }
    localStorage.setItem('theme', this.theme);
  }
}

You probably should inject localStorage via dependency injection but thats other subject.

Xesenix
  • 2,418
  • 15
  • 30
  • How to set light theme as default? If i don't set a defualt theme, i can't see any theme – mantegnous Jun 25 '19 at 09:14
  • `theme: string = localStorage.getItem('theme') || 'Light';` this should work if theme is undefined it will use whatever is on right side of `||` – Xesenix Jun 25 '19 at 11:16
0

You can use it like this --> localStorage.setItem('name', item); https://developer.mozilla.org/de/docs/Web/API/Window/localStorage

frobi
  • 23
  • 6
0

You can also use angular-storage npm page to store data.

store.set('number', 2)

https://www.npmjs.com/package/angular-storage

It's simple to use and read.

Major banifit is that u can store object, number etc

Hassan Ali
  • 994
  • 6
  • 22