Using localStorage Object To Keep Data in the Browser

Posted By : Vinit Kumar Bhagat | 29-May-2022

ERP

Loading...

In our Angular applications, remembering user preferences is an excellent way to provide good information to users. We can store data in a user's browser using Local Storage, which provides keyword processing methods.

To understand how Local Storage works, we need to learn about this API and use the information to create an Angular to save background color preferences.

Local Storage API


The Local Storage Object helps us to store data, and this API provides four ways to help us integrate with the data stored in the browser. We will go through each of them, showing an example of how it is used:

  • setItem
  • getItem
  • removeInto
  • clear

setItem
The setItem method (key, value) helps us add value to local storage using key and value. For example, the following code saves the main user background and #ff00ff value in local browser storage.

Example:

localStorage.setItem ('background-user', '# ff00ff')


If you need to save things, first you need to convert to a character unit using JSON.stringify.
Important: Data stored in the browser has no expiration date and is stored in 5 MB of domain storage.

getItem
The getItem (key) method helps us to read and expect the keyword to return data to local storage.

Example:

localStorage.getItem ('background-user')


removeInto
The removeItem (key) method helps us to remove a key and a value; waiting for a keyword to remove it from the browser endpoint.

Example:

localStorage.removeItem ('background-user')


clear
The explicit method () removes all keys, and does not expect any restrictions to remove all keys stored in the browser.

Example:

localStorage.clear ()


DONE! With a complete picture of the LocalStorage API, let's move from theory to work.

Using Angular Local Storage Power


We will build an Angular application that allows the user to change the background color, remember it and reset it, so we need some actions on our part.

  • Create an HTML tag: It has an HTML color picker feature and a button for the user to select a color and reset values.
  • The TypeScript file works with the LocalStorage API and provides storage, upload and extraction methods for LocalStore.

ComponentMarkup


First, add a component of the HTML color checker to allow the user to select a color and declare a variant of the #colorPicker template.

It helps to work with the color picker to find and set value. Listen to the change event and link to the saveBackgroundColor method.

SaveBackgroundColor method gets a flexible reference and takes the color selector element to save the selected color.

Next, add the HTML Button item, listen to the Click event, and link to removePreferences (). It will call our TypeScript code to remove the values.

The code will look like this:

<div class = "container">
<div class = "row">
<h1> Angular and Local Storage </h1>
<p> We, save your background color, if you want to restore :) </p>
</div>
<div class = "row">
<entries
type = "color"
#colorPicker
[value] = "Color Background User"
(change) = "save Background (colorPicker.value)"
/>
</div>
<button class = "btn-remove" (click) = "removePreferences ()">
Delete favorites
</button>
</div>


Methods and Events Part


This step will announce HTML tagging methods, use Angular life cycle hooks, work with the LocalStorage API, and announce the flexibility and modes to provide the expected backlash and popular backgrounds.

Variable
As we learned in the storage API, it works with pairs of key values. First, announce the storeKey variable as the 'User background' value value.

Next, create a Color variable to give the background automatically and user BackgroundColor to render the selected value in the color selector.

private storageKey = 'user domain';
private defaultColor = '# ff00ff';
userBackgroundColor = null;


TypeScript Component and Concept Methods
Our HTML markup section requires two main community modes, but we will create other ways to provide full functionality.

  • getBackgroundColor: Find the background in LocalStore or restore the default color.
  • loadBackgroundPreferences: Assign selected color to the color selector section and update the background color of the page.
  • deletePreferences: Remove keys from storage and reload pre-user preferences.
  • saveBackgroundColor: Save the selected color and upload your background color preferences.


First, the getBackgroundColor method uses localStorage.getItem() to read the placement key. If present, it returns the value; otherwise it returns the Color variable.

private getBackgroundColor (): character unit {
restore localStorage.getItem (this.storageKey) || this.defaultColor;
}


Next, create a loadBackgroundPreferences() path. Gives the user a different color of the getBackgroundColor() value back and removes the background color of the body.style.in the User Background Color.

To load a dried or saved color, drive the path to the OnInit life cycle chicken.

ngOnInit(): none {
this.loadBackgroundPreferences ();
}
private loadBackgroundPreferences (): void {
this.userBackgroundColor = this.getBackgroundColor ();
window.document.body.style.backgroundColor = this.getBackgroundColor ();
}


Finally, announce the last two public modes, saveBackgroundColor and deletePreferences.

saveBackgroundColor is linked to an event (change) from the color selector, passing the value.

Using the setItem() method in local storage, save the color key with the color value and call the loadBackgroundPreferences() method to load user preferences.

public saveBackgroundColor (color: string): void {
localStorage.setItem (this.storageKey, color);
this.loadBackgroundPreferences ();
}

We enter each path to have the expected behavior, and the final code looks like this:

import { Component } from '@angular/core';

@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
})
export class AppComponent {
 private storageKey = 'user-background';
 private defaultColor = '#bedac9';
 userBackgroundColor = null;

 ngOnInit(): void {
   this.loadBackgroundPreferences();
 }
 private loadBackgroundPreferences(): void {
   this.userBackgroundColor = this.getBackgroundColor();
   window.document.body.style.backgroundColor = this.getBackgroundColor();
 }
 removePreferences(): void {
   localStorage.removeItem(this.storageKey);
   this.loadBackgroundPreferences();
 }
 saveBackgroundColor(color: string): void {
   localStorage.setItem(this.storageKey, color);
   this.loadBackgroundPreferences();
 }
 private getBackgroundColor(): string {
   return localStorage.getItem(this.storageKey) || this.defaultColor;
 }
}

We have learned and built a real case for using local Storage in our applications.

Thanks for your time. I hope it helps you learn how to work with local storage and create a better user experience in your apps.