Avatar

Rhett Harrison

Software Engineer

Read Resume

Local Storage with Angular

thumbnail

I recently created a small chat application to teach students at Arizona State University about LocalStorage

Introduction

I was recently asked to speak at Arizona State University at their student led organization named CodeDevils. Given the interest in Angular and LocalStorage, I developed a chat application that uses LocalStorage as a realtime database. While LocalStorage isn't suited for multi-device synchronization, it works well for demonstrating concepts and storing user preferences like Dark Mode or Accessibility Settings.

Setting up the Project

First, we need to install Node.js and Angular CLI. Download the LTS version of Node.js from its website

With Node.js installed, install Angular CLI using the following command:

You can find the full code for this project on my GitHub

What is LocalStorage?

LocalStorage is a property on the window object that can be modified through four methods:

It stores key-value pairs specific to the website domain and protocol, accessible across multiple tabs and browser windows on the same device. For instance, the localStorage object for https://rhettharrison.com is different from http://rhettharrison.com due to different protocols.

How to achieve this in Angular

Signals are a new feature introduced in Angular version 16 and fully supported in version 17. This application was built using Angular version 18, leveraging the Signals feature. More details on Signals can be found in the Angular documentation site.

I used LocalStorage to keep track of users and messages in the chat application. Here's an example with users. Refer to home.component.ts in the linked repository.

First, create a signal for the messages by calling localStorage.getItem('messages'). If the item doesn't exist, initialize the signal with an empty array.

Next, implement an Effect to update LocalStorage whenever the #messages signal is updated.

Finally, update the signal when the LocalStorage object changes by listening for the window.storage event using the @HostListener decorator. This ensures that every tab is notified of changes.

Conclusion

With these steps, you can manage signals in Angular components and synchronize them using LocalStorage, sharing data across tabs and browser windows. This is ideal for user preferences, accessibility settings, and more.

2024 — Crafted from Sonora, CA