Skip to content

Storage (Local, Session)

With Web Storage, web apps can store data locally within the user’s browser. Objects like Local Storage and Session storage allow saving key-value pairs in the browser.

Data stored in Local Storage has no expiration time and so saved data will persist even after we close the browser windows. The data stored is bound to an origin, Which means that the localStorage is unique per protocol://host:port

Unlike cookies, localStorage isn’t sent to the server in every request like cookies so browsers do allow storing up to 5MB of data.

localStorage.setItem(name, value);set the value for a name
localStorage.removeItem(name);remove the name-value pair identified by name.
localStorage.getItem(name);get the value for a given name.
localStorage.key(index)get the name of the value in the given numeric position.
localStorage.clear()remove all values.

Let’s Create a mini demo APP


<!DocTYPE html>
<html lang="en">

    <title>Test Local Storage</title>

    <h1>Testing Local Storage</h1>
    <script src="script.js"></script>



'use strict'

//saving data to local Storage
for (let i = 0; i < 5; i++) {
    localStorage.setItem('Local ' + i, 'We are trying to store a key value pair');

const el = document.createElement('div');
el.innerHTML = '<p>Local Storage is created. Check Developer tools to access the data</p>'
const container = document.querySelector('body');

//retriving data using a key
console.log(localStorage.getItem('Local 1'));

// //accessing all the keys of a origin/domain
for (let i = 0; i < localStorage.length; i++) {
    console.log(`Key: ${localStorage.key(i)}
Value: ${localStorage.getItem(localStorage.key(i))}`);

//removing element using a key
localStorage.removeItem('Local 1');

//remove all elements

let’s see a comparison between Local Storage, Session Storage and cookies

Angular App:

We need to create a form which can persist data on close, Refresh and navigation to different page i.e. if user has modified a form without saving if he navigates to different page or closes the page all together and again when he opens the form, it should contain the user’s last entered data.

app.component.html: Holds Reactive Form


<form [formGroup]='MessageForm' (ngSubmit)="onSave()">
      <th id="form1">
      <td><label for="Username">Username</label></td>
      <td><input type="text" name='Username' formControlName='Username'></td>
      <td><label for="Subject">Subject</label></td>
      <td><input type="text" name='Subject' formControlName='Subject'></td>
      <td><label for="Body">Body</label></td>
      <td><textarea name="Body" formControlName="Body" cols="30" rows="10"></textarea></td>


app.component.ts: Holds our logic related to persistence (save, window closed) and reactive form data.

import { Component, HostListener, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent implements OnInit {
  title = 'WakeUp';
  constructor(private fb: FormBuilder) { }

  @HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) {
    if (this.MessageForm.dirty) {
      //store data
      localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));
      //show popup
      $event.returnValue = true;

  ngOnInit(): void {
    //retrieves data if exists.
    if (localStorage.getItem('teja')) {

  MessageForm ={
    Username: [''],
    Subject: [''],
    Body: ['']

  onSave() {

    //removes the data with key as user

    //adds new data with key as user
    localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));

    //reset form once form is edited dirty flag is set 
    //so we need to reset form else on close we get 
    //notification saying form is dirty even when user clicked on save
  • When a user clicks on save we will be calling onsave method we first clear the old data and then stores the new form data.
  • While Storing we are storing the entire form so we need to convert the form into a JSON string. so we are using JSON.stringify
  • once stored we are resetting the form, this is required to reset the form flags like dirty, untouched, and so on.
  • With ngOnInit whenever this component gets loaded we are prepopulating the form with the data we have in local storage.
  • in case the user updates the form without saving and he tries to close the window, we are handling this condition by reading the close operation using HostListener. Check if the form is modified using the dirty flag and then save the data to localStorage.

app-routing.ts: This handle the routing

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AppComponent } from "./app/app.component";
import { UnsavedataGuard } from "./_guard/unsavedata.guard";

const routes: Routes = [
    { path: '', component: AppComponent, canDeactivate: [UnsavedataGuard] },
    { path: '**', component: AppComponent, pathMatch: 'full' }

    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
export class AppRoutingModule { }

We are gonna apply the canDeactivate to our path to get notified when someone navigates out.

Unsavedata.ts: Logic to handle navigation to different page.

import { AppComponent } from './../app/app.component';
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';

  providedIn: 'root'
export class UnsavedataGuard implements CanDeactivate<unknown> {

    component: AppComponent): boolean {
    if (component.MessageForm.dirty) {
      localStorage.setItem("teja", JSON.stringify(component.MessageForm.value));
      return confirm('Are you sure you want to continue? Any unsaved changes will be lost');
    return true;

The above guard is created by using the command “ng g guard unsaveddata” and inheriting from Candeactivate. When someone navigates out we will check if the form is dirty if so we save the data.

Note: With Host Listener and CanDeactive we are also showing a additional popup box to notify the user that he has unsaved data.

Published inUncategorised

Be First to Comment

Leave a Reply

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