Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to use local storage in angular

How to use local storage in angular ?

Aman Jain, April 18, 2022October 4, 2022

Local storage are used to store client side data in browser and in this tutorial we will learn to use local storage in angular. Angular is a javascript framework and used to enable to seamless developer experience to build web and mobile applications. Local storage are useful when we want to store large data up to 5 mb per domain.

we can store key value in client system and javascript provides simple APIs to access the local storage feature of browser.

Difference between cookies and local storage ?

Cookies are also stored in client browser but there are some difference in local storage and cookies. Cookies can be store in browser 4,096 bytes and sent with each request to server so if the cookies are big in size than it can increase the request size too whereas local storage are big in size which is 5 mb. Local storage can only be useful when we only want store data of user or website on client side and then want to access back on client side.

Simplest way to set storage

localStorage.setItem(key,value);

Simplest way to get storage

localStorage.getItem(value);

So let’s start set and get use of local storage in angular

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 3: Create component

Now, create two components one for set the cookie and other for get the cookie in different pages

ng g c SetStorageExample

This will create a folder in app directory named with set-cookie-example and here is component file

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

@Component({
  selector: 'app-set-storage-example',
  templateUrl: './set-storage-example.component.html',
  styleUrls: ['./set-storage-example.component.css'],
})
export class SetStorageExampleComponent implements OnInit {
  constructor() {}

  ngOnInit() {
    localStorage.setItem('user', 'Readerstacks');
  }
}

here we localstorage.setItem on ngOnInit method for demo purpose

localstorage.setItem('user', 'Readerstacks');

Html to link to another page

<p>We have set local storage on this page</p>
<a routerLink="get-storage">Get storage to another page</a>

Create another component to get the local storage

ng g c GetStorageExample

This will create a folder in app directory named with get-cookie-example and here is component file

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

@Component({
  selector: 'app-get-storage-example',
  templateUrl: './get-storage-example.component.html',
  styleUrls: ['./get-storage-example.component.css'],
})
export class GetStorageExampleComponent implements OnInit {
  user: string;

  constructor() {}

  ngOnInit() {
    this.user = localStorage.getItem('user');
  }
}

we fetched the stored value in local storage using this.user =localStorage.getItem('user');

Html to display name

<p>Getting storage on this page</p>
User : {{ user }}

Step 4: Add routes in app routing

Finally add the routes in app.routing.module.ts to test the implementation

import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SetStorageExampleComponent } from './set-storage-example/set-storage-example.component';
import { GetStorageExampleComponent } from './get-storage-example/get-storage-example.component';

@NgModule({
  declarations: [SetStorageExampleComponent, GetStorageExampleComponent],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      { path: '', component: SetStorageExampleComponent },
      { path: 'get-storage', component: GetStorageExampleComponent },
    ]),
  ],
  exports: [RouterModule],
  providers: [],
})
export class AppRoutingModule {}

Run the application and check implementation

Create Injectable Service to use Local Storage

We can also create a injectable service across the components so that we can reuse the service in our all components.

let’s create a service

ng g s LocalStorage
import { Injectable } from '@angular/core';

@Injectable()
export class LocalStorageService {
  constructor() {}

  set(key: string, value: any) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch (err) {
      console.error('Error while setting local storage', err);
    }
  }

  get(key: string): any {
    try {
      return JSON.parse(localStorage.getItem(key));
    } catch (err) {
      console.error('Error while getting local storage key ', key, err);
      return '';
    }
  }
}

Using in component

 ngOnInit() {
    
    this.storage.set("user_object",{id:1,name:"reader",email:"info@readerstacks.com"});
  }

As you can see here we have set object in key value.

and get the value

 ngOnInit() {
    
    this.storage.get("user_object");
  }

Don’t forget to add in provider of routing module or app.module.ts file


@NgModule({
 .....
  providers: [LocalStorageService],
..
})

Live : https://stackblitz.com/edit/set-and-get-local-storage-in-angular-readerstacks

Screenshot 2022 04 18 at 9.40.20 PM
Screenshot 2022 04 18 at 9.40.28 PM
set and get local storage in angular
beenhere

Also Read:

How to set and get cookies in angular ?

Related

Javascript Angular angularlocalstorage

Post navigation

Previous post
Next post

Related Posts

jQuery redirect after Ajax success Laravel PHP

December 4, 2021December 4, 2021

In this article i will show you to redirect a page after successful response from Ajax request. Laravel or PHP provides itself to redirect a page using its own methods but while working with JavaScript Ajax Laravel methods are not useful because it won’t redirect the page. so in this…

Read More
Javascript Angular KeyUp Event on Input Example

Angular KeyUp Event on Input Example

September 22, 2022March 16, 2024

Angular KeyUp Event on Input is an Angular event binding it triggers when user interacts with DOM like text based input element and when we key up the input. Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular KeyUp…

Read More

Show dropdown list from ajax response in jQuery

September 10, 2021September 10, 2021

Showing Dynamic Select Box using jQuery and Php,MySql In this tutorial, we are going to learn the dropdown list using AJAX. Loading dropdown values from AJAX requires knowledge of javascript, jQuery, php and html. Sometimes it requires to load the dropdown like countries, state, city list dependently. In this case…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version