Categories

Thursday, April 18, 2024
#919814419350 therichposts@gmail.com
Angular6

Best Practice for Localstorage in Angular

Best Practice for Localstorage in Angular - The Rich Post

Hello to all, welcome to therichpost.com. Today In this post, I will tell you, Best Practice for Localstorage in Angular.

I am doing this functionality in angular 6 application.

Localstorage is use to store data with no expiration date. We will manually destroy it.

In this post, I am creating and deleting the local storage data and it is easy to use.

Here is the working Image just for testing:

 

Best Practice for Localstorage in Angular

 

In above picture, there are two buttons, Get item and Delete item:

Get Item is set the value for variable.

Delete Item is remove the value from variable.

 

Here is the working and tested code, you need to follow:

 

1. First, you need to write below code into yours app.component.ts file:

Here,  we will set the localstorage data and also delete it:

import {Component} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  get dataV(): any {
    return localStorage.getItem('blog');
  }
  
  delete()
  {
   
    localStorage.removeItem('blog');
  }
  get()
  {
    
    localStorage.setItem('blog', 'therichpost.com');
  }
}

 

2. Second, you need write below code into your app.component.html file:

In this file, we will make the buttons and get the localstorage data:

<div class="jumbotron text-center">
  <h1>Angular LocalStorage
</h1>
</div>
<div class="container">
<button (click)="get()">Get Item</button><br><br>
<button (click)="delete()">Delete Item</button>
<h1>{{ dataV }}</h1>
</div>

 localstoragedata

If you have any query related to this post, then do comment below or ask questions.

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.