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

Angular form validation with example

August 30, 2021August 30, 2021

Angular has in-build form validation rules to validate the inputs and show errors in the ui with ease. Before reading you should have knowledge of angular, installation process, components and angular FormGroup. Steps to create a reactive form in angular Create a new or existing angular project, you can also…

Read More
Javascript ngFor and For loop over object or Array in angular

ngFor and For loop over object or Array in angular

March 30, 2022October 4, 2022

Loops are used to iterate through objects or array, In angular we can use ngFor and For loop over array or object in angular, ngFor is a template structural directive which is used to iterate a loop in template file whereas for and each is used to iterate the loop…

Read More

How many type of methods in Restful api?

August 28, 2021February 22, 2024

Restful api is very useful today while creating a mobile application or web application. Restful api or Http request methods There is 4 types of method of http request. Post Get Put Delete Patch 1. Post method Post method is widely used to fetch the content of a form or…

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