Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Best libraries for Angular local storage with examples

Angular local storage example

Many applications use local and session storage, in this tutorial we’ll focus on Angular local storage implementation. There are plenty of third-party libraries to implement local storage in our Angular project.

In this tutorial, we have three objectives, First how to implement Angular local storage using Browser window object, secondly we’ll implments some of most popular 3rd parties libraries for local storage, and lastly Angular local storage observable.

Angular local storage example using window localStorage

Let first create our Angular local storage project. Before starting an angular project you need to install nodejs and Angular CLI in your system. Let create the project for local storage.

ng new localStorageApp

HTML 5 allows us to store data within a browser window and before HTML5 we use cookies to store local data in the browser. The Web storage of HTML 5, provide us to use both( local and session) storage and is more secure and faster than doing the same via cookies. In web storage allow us to store data locally in the browser and we have two types.

  1. Window.localStorage : Stores data in the browser with no expiration date.
  2. Window.sessionStorage : Stores data in the browser just for the current session.

Web storage objects: localStorage and sessionStorage allows us to store data in key/value pairs in the browser. The localStorage is a read-only property of the window interface, allowing us to access a Storage object for the Document’s origin; the stored data is saved across browser sessions.

Here is a screenshot of our local storage example one.

Angular local storage example

The localStorage the property allows you to save key/value pairs in a web browser. In our above example what we are achieving.

  1. How to store a variable and object value to localStorage.
  2. How to retrieve localStorage data and objects.
  3. How to remove Item from local storage.
  4. How to clear local storage data.
Note : Window.localStorage data has no expiration time and it will persist to store data even we close window. Only way to remove is calling removeItem with key or clear() method on storage.

Step 1: Create Angular local storage service.

Let’s create an Angular storage service, so that we can use this local storage data across our application.

cd localStorageApp
ng generate service services/localStorage

Let’s add the following methods to our Angular local storage service: local-storage.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {

  getItem(key: string) {
    const item = localStorage.getItem(key);
    return (item) ? JSON.parse(item) : null;
  }

  setItem(key: string, value: any): void {
    localStorage.setItem(key, JSON.stringify(value));
  }

  removeItem(key: string): void {
    localStorage.removeItem(key);
  }

  clear() {
    localStorage.clear();
  }
}

Both web storage objects provide the same methods and properties. Here we have listed the methods and properties of Window.localStorage.

Methods/PropertiesDescription
setItem(key, value)The set method saves data in key and value pairs in Browser.
getItem(key)Get saved data from localStorage using the key as an argument.
removeItem(key)This method removes items from localStorage using the key as an argument.
clear()Remove all items of localStorage of particular sites in the browser.
key(index)Get the key in a given position.
lengthReturn the length or number of stored items in localStorage.

Step 2: Consume Storage service in our component

Once, we have a local storage service, we can consume storage service in the app.component.ts file and for that, we need to import storage service in the component constructor.

import { Component } from '@angular/core';
import { LocalStorageService } from './services/local-storage.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  person = { name: '', country: ''};
  storageName: string | undefined;
  storageObject: Object = {};

  constructor(
    private storage: LocalStorageService
  ) { }

  setStorage() {
    this.storage.setItem('name', this.person.name);
    this.storage.setItem('person', {
      name: this.person.name,
      country: this.person.country
    });
    alert('Set storage variable and object successfull');
  }

  getStorage() {
    this.storageName = this.storage.getItem('name');
    this.storageObject = this.storage.getItem('person');
  }

  removeItemStorage(key: string) {
    this.storage.removeItem(key);
  }

  clearAllStorage() {
    this.storage.clear();
    this.storageName = '';
    this.storageObject = {};
  }
}

Step 3: Add form input for storage operation

Let add a form in the app.component.html to add two inputs one for name and country. We have added a few buttons to perform storage operations.

<div class="container">
  <h3>Angular storage using window object</h3>
  <form #userForm="ngForm" class="form">
    <div class="form-group">
      <label>Name</label>
      <input class="form-control" [(ngModel)]="person.name" name="name" #nameCtrl="ngModel">
    </div>
    <div class="form-group">
      <label>Country</label>
      <input class="form-control" [(ngModel)]="person.country" name="email" #emailCtrl="ngModel">
    </div>
  </form>

  <div class="d-md-flex justify-content-md-end">
    <button type="button" class="btn btn-primary btn-sm" (click)="setStorage()">Set storage data</button>
    <button type="button" class="btn btn-primary btn-sm"(click)="getStorage()">
       Get storage data
    </button>

    <button type="button" class="btn btn-primary btn-sm" (click)="removeItemStorage('name')">
     Remove name local storage
     </button>
    <button type="button" class="btn btn-primary btn-sm" (click)="clearAllStorage()">
     Clear all storage
    </button>
  </div>

  <div>
    <p>Storage name: {{ storageName }}</p>
    <p>Storage Object: {{ storageObject | json }}</p>
  </div>
</div>

Angular local storage example using ngx-webstorage

Let’s demonstrate the second Angular storage example using the ngx-webstorage. We will have the same activities as the previous example, except we also implemented Angular local storage observable using the ngx-webstorage. Here is a screenshot of the ngx-webstorage example.

ngx webstorage service angular

Let’s first install the ngx-webstorage in our Angular project.

npm i ngx-webstorage --save

We also need to configure and import NgxWebstorageModule inside the app.module.ts file.

....
import { FormsModule } from '@angular/forms';
import { NgxWebstorageModule } from 'ngx-webstorage';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    FormsModule,
    NgxWebstorageModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now let’s edit our local storage service and also add code for Angular local storage observable also.

import { Injectable } from '@angular/core';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  constructor(private lStorage: LocalStorageService) {}

  saveValue(key: string, value: string) {
    this.lStorage.store(key, value);
  }

  retrieveValue(key: string) {
    return this.lStorage.retrieve(key);
  }

  removeValue(key: string): void {
    this.lStorage.clear(key);
  }

  clear() {
    this.lStorage.clear();
  }

  observeStorageIten(key: string) {
    return this.lStorage.observe(key);
  }
}

In our service, we need to import our the localStorageService and we have also added Angular local storage observable on the storage key name. Whenever the name key of the local storage changes its value, we call local storage observable on the key name. Let’s edit the component typescript file.

import { Component, OnInit } from '@angular/core';
import { StorageService } from './services/storage.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  person = { name: '', country: '' };
  storageName: string | undefined;
  storageObject: any;

  constructor(
    private storage: StorageService
  ) { }


  ngOnInit(): void {
    this.storage.observeStorageIten('name')
      .subscribe((value) => {
        if (value) 
          alert('Set new value to local storage key name : ' + value);
      });
  }

  setStorage() {
    // To save string
    this.storage.saveValue('name', this.person.name);

    // To save object, need to convert to string
    this.storage.saveValue('person', JSON.stringify({ name: this.person.name, country: this.person.country }));
    alert('Set storage variable and object successfull');
  }

  getStorage() {
    this.storageName = this.storage.retrieveValue('name');
    this.storageObject = JSON.parse(this.storage.retrieveValue('person'));
  }

  removeItemStorage(key: string) {
    this.storage.removeValue(key);
  }

  clearAllStorage() {
    this.storage.clear();
    this.storageName = '';
    this.storageObject = {};
  }
}
Note : In ngx-webstorage, we don’t have removeItem, instead we can use clear with key to remove particular key item element in local storage. The clear() method without any key will remove all item from local storage.

Angular local storage example using @ngx-pwa/local-storage

Angular does not provide a client-side storage module, and almost every app needs some client-side storage. There are 2 native JavaScript APIs available:

  • localStorage
  • indexedDB

The localStorage API is simple to use but synchronous, using it too often, may soon freeze our apps. The indexedDB API is asynchronous and efficient, but it’s a mess to use: you’ll soon be caught by the callback hell, as it does not support Promises yet.

Mozilla has done a very great job with the localStorage library: a simple API based on native localStorage, but internally stored via the asynchronous indexedDB for performance. This module is based on the same idea as localForage, but built-in ES6+ and additionally wrapped into RxJS Observables to be homogeneous with other Angular modules.

Let start a new project, add or install the @ngx-pwa/local-storage in our Angular project.

# For Angular LTS (Angular >= 10):
ng add @ngx-pwa/local-storage

Let’s edit the local storage service that is storage.service.ts

import { Injectable } from '@angular/core';
import { StorageMap } from '@ngx-pwa/local-storage';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  constructor(private storage: StorageMap) { }

  setItem(key: string, value: string) {
    return this.storage.set(key, value);
  }

  getItem(key: string) {
    return this.storage.get(key);
  }

  removeItem(key: string) {
    return this.storage.delete(key);
  }

  observeItem(key: string) {
    return this.storage.watch(key);
  }

  clear() {
    return this.storage.clear();
  }
}

This library allows Angular local storage observable also. Now let’s consume the local storage service in our component typescript file. In all examples, we have used the same component template for form and button. Let’s edit the app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { StorageService } from './services/storage.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  person = { name: '', country: '' };
  storageName = '';
  storageObject: any;

  constructor(
    private storage: StorageService
  ) { }


  ngOnInit(): void {
    // Add observable
    this.storage.observeItem('name')
      .subscribe((value) => {
        if (value) 
          alert('Set new value to local storage key name : ' + value);
      });
  }

  setStorage() {
    // To save string
    this.storage.setItem('name', this.person.name).subscribe(() => {});

    // To save object, need to convert to string
    this.storage.setItem('person', JSON.stringify({ name: this.person.name, country: this.person.country }))
    .subscribe(() => {});
  }

  getStorage() {
    this.storage.getItem('name').subscribe((data: any) => {
      if (data) {
        this.storageName = data;
      }
    });
   
    this.storage.getItem('person').subscribe((data: any) => {
      if (data) {
        this.storageObject = JSON.parse(data);
      }
    });
  }

  removeItemStorage(key: string) {
    this.storage.removeItem(key).subscribe(() => {
      this.storageName = '';
    });
  }

  clearAllStorage() {
    this.storage.clear().subscribe(() => {
      this.storageName = '';
      this.storageObject = {};
    });
  }
}
Check articles on the best and latest 2022, and 2021 Angular books to read for your journey from beginner to advanced level. BEST BOOK ON ANGULAR 2022 – 2021

Conclusion
We have learned how to implement Angular local storage with service and for the Window.localStorage we don’t need to add Window as a prefix on localStorage. I hope you got some idea about how to implement Angular local storage.

Related Articles

Best libraries for Angular local storage with examples

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top