Angular 6 : Local Storage
Sometime, we need to store some data in client side, so we can use cookie and local storage,
Here is the example of local storage.
Component
export class LocalStorageComponent implements OnInit {
constructor() { }
ngOnInit() {
//remove value if exists
//localStorage.removeItem('loggedInUser');
}
setlocalstorage() : void{
let userObj = { name: 'Rohit', lname: 'Rathod' };
localStorage.setItem('loggedInUser', JSON.stringify(userObj));
}
getlocalstorage() : void{
if (localStorage.length > 0)
{
// We have items
let item = JSON.parse(localStorage.getItem('loggedInUser'));
if(item != null)
{
console.log(item)
console.log(item.name)
console.log(item.lname)
}
}
else
{
// No items
alert('no local data')
}
}
}
HTML
<button (click) = "setlocalstorage()">Set Storage</button>
<button (click) = "getlocalstorage()">Get Storage</button>
Hope this will help you and save your time.
Enjoy !!!
:)