Angular Basics: Using localStorage Object To Keep Data in the Browser

Learn how to save user-preferred settings and data in the browser with the localStorage API in Angular.


This content originally appeared on Telerik Blogs and was authored by Dany Paredes

Learn how to save user-preferred settings and data in the browser with the localStorage API in Angular.

In our Angular apps, remembering user-preferred settings is an excellent way to provide a good experience for the users. We can save data in the user’s browser using the localStorage object, which provides methods for working the key-value data.

To understand how localStorage works, we need to learn about this API and use the knowledge to build an Angular to save background color preferences.

The Local Storage API

The localStorage object helps us store data, and this API provides four methods to help us interact with the data stored in the browser. We’ll go over each of them, showing an example of how to use it:

  • setItem
  • getItem
  • removeItem
  • clear

setItem

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

Example:

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

If you need to store objects, first you need to convert to string using JSON.stringify.


Important: The data stored in the browser doesn’t have an expiration date and is capped at 5 MB of storage for the domain.

getItem

The getItem(key) method helps us read and expects the key name to return the data in local storage.

Example:

localStorage.getItem('user-background')

removeItem

The removeItem(key) method helps us remove the key and the value; it expects the key name to remove it from the browser’s local storage.

Example:

localStorage.removeItem('user-background')

clear

The clear() method removes all keys, and it does not expect any parameters to delete all keys stored in the browser.

Example:

localStorage.clear()

DONE! With the complete picture of the localStorage API, let’s move from theory to practice.

Using the Power of LocalStorage With Angular

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

  • Create HTML markup: It has a color picker HTML element and a button for the user to pick a color and reset values.
  • The TypeScript file interacts with localStorage API and provides the methods for saving, loading and removing the values from localStorage.

Let’s work!

The Component Markup

First, we add an element of HTML Color picker to allow the user to pick a color and declare a template variable #colorPicker.

It helps to interact with the color picker to get and set a value. Listen for the Change event and link it with the saveBackgroundColor method.

The saveBackgroundColor method receives the reference variable and takes the value color picker element to save the selected color.

Next, add an HTML Button element, listen for the Click event, and link with the 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 LocalStorage</h1>
<p>We, save your background color, if you want returns :) </p>
 </div>
 <div class="row">
   <input
     type="color"
     #colorPicker
     [value]="userBackgroundColor"
     (change)="saveBackgroundColor(colorPicker.value)"
   />
 </div>
 <button class="btn-remove" (click)="removePreferences()">
   Remove preferences
 </button>
</div>

Read more about previous topics:

Component Methods and Events

This step will declare methods for HTML markup, use the Angular lifecycle hooks, work with the localStorage API, and declare variables and methods to provide the expected behavior of saving and loading background preferences.

Variables

As we learned from the local Storage API, it works with key-value pairs. First, declare the storageKey variable as a key with the 'user-background' value.

Next, create defaultColor variable to provide background by default and userBackgroundColor to assign the selected value to the color picker.

private storageKey = 'user-background';
private defaultColor = '#ff00ff';
userBackgroundColor = null;

Component TypeScript Methods and Logic

Our component HTML markup needs two main public methods, but we will create other methods to provide the full functionality.

  • getBackgroundColor: Get the background from localStorage or return the default color.
  • loadBackgroundPreferences: Assign the selected color to the color picker element and update the page background color.
  • removePreferences: Remove the keys from local storage and reload the background user preferences.
  • saveBackgroundColor: Save the selected color and load the background color preferences.

First, the getBackgroundColor method uses the localStorage.getItem() to read the storageKey. If it exists, it returns the value; otherwise it returns the defaultColor variable.

private getBackgroundColor(): string {
return localStorage.getItem(this.storageKey) || this.defaultColor;
}

Next, create loadBackgroundPreferences() method. It assigns to userBackgroundColor variable the getBackgroundColor() return value and overrides the body.style.background color with the userBackgroundColor value.

To load the default or saved color, call the method into the ngOnInit lifecycle hook.

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

Finally, declare the last two public methods, saveBackgroundColor and removePreferences.

The saveBackgroundColor is linked with the (change) event from the color picker, passing the value.

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

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

The button uses The removePreferences method in the markup. It removes the key from the localStorage using the removeItem method and reloads the preferences.

We should use localStorage.clear(), but it removes all keys. In our case, we only want to delete the single one.

public removePreferences(): void {
localStorage.removeItem(this.storageKey);
this.loadBackgroundPreferences();
}

We dove into each method 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;
 }
}

Conclusion

We learned about and built a real use case for localStorage in our apps. You can find a full code example for this article and play with the example app in the following links:

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


This content originally appeared on Telerik Blogs and was authored by Dany Paredes


Print Share Comment Cite Upload Translate Updates
APA

Dany Paredes | Sciencx (2022-05-25T13:33:02+00:00) Angular Basics: Using localStorage Object To Keep Data in the Browser. Retrieved from https://www.scien.cx/2022/05/25/angular-basics-using-localstorage-object-to-keep-data-in-the-browser/

MLA
" » Angular Basics: Using localStorage Object To Keep Data in the Browser." Dany Paredes | Sciencx - Wednesday May 25, 2022, https://www.scien.cx/2022/05/25/angular-basics-using-localstorage-object-to-keep-data-in-the-browser/
HARVARD
Dany Paredes | Sciencx Wednesday May 25, 2022 » Angular Basics: Using localStorage Object To Keep Data in the Browser., viewed ,<https://www.scien.cx/2022/05/25/angular-basics-using-localstorage-object-to-keep-data-in-the-browser/>
VANCOUVER
Dany Paredes | Sciencx - » Angular Basics: Using localStorage Object To Keep Data in the Browser. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/05/25/angular-basics-using-localstorage-object-to-keep-data-in-the-browser/
CHICAGO
" » Angular Basics: Using localStorage Object To Keep Data in the Browser." Dany Paredes | Sciencx - Accessed . https://www.scien.cx/2022/05/25/angular-basics-using-localstorage-object-to-keep-data-in-the-browser/
IEEE
" » Angular Basics: Using localStorage Object To Keep Data in the Browser." Dany Paredes | Sciencx [Online]. Available: https://www.scien.cx/2022/05/25/angular-basics-using-localstorage-object-to-keep-data-in-the-browser/. [Accessed: ]
rf:citation
» Angular Basics: Using localStorage Object To Keep Data in the Browser | Dany Paredes | Sciencx | https://www.scien.cx/2022/05/25/angular-basics-using-localstorage-object-to-keep-data-in-the-browser/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.