angular
  1. angular-localstorage

Angular LocalStorage

Introduction

LocalStorage is a type of web storage that allows JavaScript websites and apps to store and access data right in the browser, without the need for a backend server or a database. In this guide, we will explore how to use LocalStorage in Angular applications.

Syntax

// store value in local storage
localStorage.setItem('key', 'value');

// retrieve value from local storage
localStorage.getItem('key');

// clear storage
localStorage.clear();

Example

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

@Component({
  selector: 'app-root',
  template: `
    <input type="text" [(ngModel)]="name" placeholder="Enter your name" />
    <button (click)="saveName()">Save</button>
    <div *ngIf="savedName">Your name is {{ savedName }}</div>
  `
})
export class AppComponent {
  name: string;
  savedName: string;

  constructor() {
    const name = localStorage.getItem('name');
    if (name) {
      this.savedName = name;
    }
  }

  saveName() {
    localStorage.setItem('name', this.name);
    this.savedName = this.name;
  }
}

Output

When the user enters their name and clicks 'Save', their name is saved in LocalStorage. If the user reloads the page, their name will still be displayed, as it was fetched from LocalStorage during initialization.

Explanation

In the example above, we have created a simple Angular component that makes use of LocalStorage. The input field allows the user to enter their name and the button saves the name in LocalStorage under the key 'name'. In the constructor, we check if there is a 'name' key in LocalStorage and if so, we display the value in the div.

Use

LocalStorage can be used in various scenarios where you need to store user data locally, such as:

  • Persisting user preferences
  • Storing user authentication tokens
  • Saving user-generated content, such as notes or bookmarks

Important Points

  • LocalStorage is not intended as a replacement for server-side storage.
  • LocalStorage has a limit of around 5-10 MB per domain, depending on the browser.
  • LocalStorage data persists even after the browser is closed, which can be useful in some cases but can also lead to security vulnerabilities if sensitive data is stored.

Summary

LocalStorage is a simple yet powerful tool for storing and retrieving data in JavaScript apps. In Angular, LocalStorage can be used to store user preferences, authentication tokens, and other types of user-generated content. Understanding how to use LocalStorage can help you create more responsive and user-friendly web apps.

Published on: