Angular LocalStorage, SessionStorage example | Ngx-web storage tutorial

This tutorial shows how to store user data in web storage in the Angular application.

In the Angular 15 tutorial, You are about to learn how to save user data to local storage and session in browsers.

Angular storage example

In this tutorial, we are going to learn the following things

  • Local storage in Angular
  • SessionStorage in Angular
  • Ngx-webstorage angular

You can check my previous post on Html5 web storage APIs with examples. LocalStroage is a browser storage mechanism to store a data

Data is stored with key and value pairs.

Angular 15 Local Storage Example

  • Step 1 Create Angular Application
  • Step 2 Install Dependencies
  • Step 3 Create Component
  • Step 4 Create Session Storage Service
  • Step 5 update App Component
  • Step 6 Start the Angular app

Create an Angular Application

If you don’t have an angular application, don’t worry; running the command below will generate one for you.

you can use the ng new command to build an Angular application

ng new angular-service-examples

Go to the project folder

cd angular-service-examples

Angular 15 ngx-webstorage example

When your application needs access to web storage APIs, you could use HTML5’s APIs directly.

However, to accommodate all use cases, you’ll need to write a lot of code. Instead, makes use of well-known libraries such as ngx-webstorage.

ngx-webstorage is an npm library and wrapper API for managing LocalStorage and SessionStorage objects from Nodejs Applications.

The advantages of using external libraries such as ngx-webstroage are When a browser doesn’t implement the Web Storage API, it utilizes the standard browser storage cookie and session cookie.

Angular applications are typescript-based. We need a library that is based on the typescript.

It provides easy services which you can integrate into your Angular application. There are a lot of other modules are there which do the same thing, but this module has support for future versions. It has support for the NPM package manager.

add ngx-webstorage to an application using npm

First, download the ngx-webstorage library using the npm command below

npm, install --save ngx-webstorage.

It installs as a project dependency and saves under the project node_module folder. --save option updates this module to package.json with the below entry under the dependencies sections.

"ngx-webstorage": "^9.0.0",

configure in Angular Application, Once installed, First need to register the module in your Root module, For that, import Ng2Webstorage in your main module.

Ng2Webstorage has different services LocalStorageService - service wrapper for LocalStorage SessionStorageService - service wrapper for SessionStorage

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { NgxWebstorageModule } from "ngx-webstorage";

@NgModule({
  imports: [BrowserModule, NgxWebstorageModule.forRoot()],
})
export class AppModule {}

Next step, Inject LocalStorageService,SessionStorageService into your component

import {Component} from '@angular/core';
import {LocalStorageService} from 'ngx-webstorage';

@Component({
    selector: 'storageTest',
    template: `





`,
})
export class StorageComponent {

    attribute;

    constructor(private storage:LocalStorageService) {}

// save the data using store methods
this.storage.store('key', 'test');

//retrieve using the key in string
 this.storage.retrieve('key');
}

instead of directly injecting it into the component, Always write a code that does all the operations related to this service in a common utility service API, so that all components can be reused like this. SessionStorageService also does the provides same methods as LocalStorageService

@LocalStorage @SessionStorage Decorators

Decorators is used to decorate classes and methods like annotations in java language. Please see the below example of how the code is updating session storage with decorators

 @SessionStorage('key')
    mykey;

    modifyValue() {
        this.mykey.push('testvalue for a key');
        this.mykey = this.mykey;
    }

The same code works in Angular 2,4,5 and 6 versions.

ngx web storage methods

The below methods are available for both local storage as well as session storage.

  • Store( key: string, value: any ): void save the key and value if the key doesn’t exist. if the key exists, update the value.
  • Retrieve( key:string ):any this retrieves the value for a specific key
  • Clear( key?: string ): void this removes storage for specific key
  • IsStorageAvailable(): boolean This returns true, if local storage/ session storage support is available returns false, if not supported
  • Observe( key?: string ): EventEmitter This returns Event Emitter and is used to observe the key of the storage object

Please ping me if you have any questions/need more clarification.