Saturday, 18 June 2016

typescript - Session Storage Angular 4/5



How to implement Session storage in this project?:
https://stackblitz.com/edit/dynamic-material-theming



When I choose the light color and close the browser and return to it - I would like the lightcolor to stay


Answer



I would use LocalStorage. Here is a link to the documentation on it. https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage




One thing it does not mention is the fact that you will run into issues if it is not supported by the browser. So make sure you handle that situation as well.



import { Component, HostBinding } from '@angular/core';
import { OverlayContainer} from '@angular/cdk/overlay';

const THEME_LOCAL_STORAGE_KEY = 'selectedTheme';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]
})
export class AppComponent {

name = 'Angular 5';
@HostBinding('class') componentCssClass;

constructor(public overlayContainer: OverlayContainer){
const theme = localStorage.getItem(THEME_LOCAL_STORAGE_KEY);


if(theme){
this.onSetTheme(theme);
}
}


onSetTheme(theme) {
this.overlayContainer.getContainerElement().classList.add(theme);
this.componentCssClass = theme;
localStorage.setItem(THEME_LOCAL_STORAGE_KEY, theme);

}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...