Cookies, Session and Local Storage in Angular

Difference between Cookies, Session and local storage

  • Cookies can store data locally upto 4kb
  • Local storage can store data upto 5mb
  • Session data is stored until the window or tabs are closed.

Cookies Storage

  • To get cookies functionality in Angular we need to install ngx cookies, command below
    npm install ngx-cookie-service –save
  • Add CookieService in provider of app.module.ts and import it
    import { CookieService } from ngx-cookie-service;
  • To get session and local storage functionality in Angular we need to install ngx-webstorage
    npm install ngx-webstorage –save
  • Add import Ng2Webstorage from ngx-webstorage

In below example we have create a text box and two buttons, on one button click we store the data into the session storage while on other button click we store the data into local storage and on second component the display both the data

  • index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SessionManagement</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';
import { SecondComponent } from './second/second.component';

@NgModule({
  declarations: [
    AppComponent,
    FirstComponent,
    SecondComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

import { SecondComponent } from './second/second.component';
import { FirstComponent } from './first/first.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [
  {path : "first", component: FirstComponent},
  {path: "second", component: SecondComponent}
];

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

app.component.html

<a routerLink="/first"> first </a> &nbsp;
<a routerLink="/second"> second </a>
<router-outlet></router-outlet>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'SessionManagement';
}

first.component.ts

import { SessionStorageService } from 'ngx-webstorage';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-first',
  template: `
<div class="container">
    <div class="row">
        <div class="col-md-3"></div>
        <div class="card border-primary mb-3">
          <div class="card-header" style="background-color: #007BFF; color : white">
            Registeration Form
          </div>
          <div class="card-body">
              <form>
                  <div class="form-row">
                      <div class="form-group">
                        <input
                          type="text"
                          class="form-control form-control-sm col-md-12"
                          id="fullName"
                          placeholder="Name"
                          [(ngModel)]="textBoxValue"
                          name="fullName">
                      </div>
                  </div>
                  <div style="text-align:center">
                    <button (click)="sessionStore()" class="btn btn-primary" >StoreSession</button> &nbsp;
                    <button (click)="localStore()" class="btn btn-primary" >LocalSession</button>
                </div>
                </form>
          </div>
        </div>
      </div>
</div>
  `,
  styles: []
})
export class FirstComponent implements OnInit {

  public textBoxValue;

  constructor() { }

  ngOnInit() {
  }

  sessionStore() {
    sessionStorage.setItem('sessiondata', this.textBoxValue);
  }
  localStore() {
    localStorage.setItem('localdata', this.textBoxValue);
  }
}

second.component.ts

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

@Component({
  selector: 'app-second',
  template: `
    <br/>Value of Session Storage Data is : {{sessionData}}
    <br/>Value of Local Storage Data is : {{localData}}
  `,
  styles: []
})
export class SecondComponent implements OnInit {
  public sessionData;
  public localData;

  constructor() { }

  ngOnInit() {
    this.sessionData = sessionStorage.getItem('sessiondata');
    this.localData = localStorage.getItem('localdata');
  }
}

Output :

After closing and opening the window only local storage in retained

Leave a Comment