Session storage is a client-side storage mechanism that allows developers to temporarily store information in the user’s browser. In Angular, we can use session storage or local storage to temporarily store data.

Scope:

Session storage is limited to the current tab or window. Data stored in session storage will get cleared when the user closes the browser or tab.

Data types:

Session storage only stores strings. Complex data like objects or arrays must be serialized (e.g., using JSON.stringify) before storage and deserialized (using JSON.parse) upon retrieval.

Security:

Sensitive data is vulnerable in session storage. Only store temporary, non-critical information.

Use Case:

In multi-step forms, store each entered value in session storage as the user progresses through the form. Upon page refresh, use stored values to automatically refill the fields.

Angular provides direct access to the browser’s session storage API through the sessionStorage property. Here’s a breakdown of its key methods:

Saving Data

To store the data in session storage we can use the setItem method.
The syntax is as follows:

sessionStorage.setItem(key: string, value: string);

For Example,
sessionStorage.setItem('username', 'john_doe');

Retrieving Data

To retrieve data from the session storage based on the key, there is the getItem method.
The syntax is as follows:

sessionStorage.getItem(key: string);

For Example,
const username = sessionStorage.getItem('username');

Deleting Data

We can use removeItem method to remove a specific data from sessionStorage by passing a key of the data to the removeItem method.

sessionStorage.removeItem(key: string);

For Example,
sessionStorage.removeItem('username');

To clear all data stored in session storage, the clear method is used.

sessionStorage.clear();

Support On Demand!

                                         
Angular