How to implement Localstorage in Angular2

In these article i explain how to use local storage in your angular project.
We need first install angular module for that you need to run the following command  “npm install angular-2-local-storage”

Browse your project using “CLI”  then run the above command or open your project in visual studio code then open integrated terminal display in below video.

After successfully install now need to open our module file called “app.module.ts” to import local-storage class.

import { LocalStorageModule } from 'angular-2-local-storage';

And import class “LocalStorageModule” like below syntax.

            prefix: 'first-app',
            storageType: 'localStorage'

Also display code in below screenshot.
Local storage module file

Now Any component you want local-storage just import “import { LocalStorageService } from ‘angular-2-local-storage’;” then assign in your constructor to use in that component like below example

import { LocalStorageService } from 'angular-2-local-storage';
    // ...
export class FirstComponent{
    constructor (
        private localStorageService: LocalStorageService
    ) {
   // use her & any function of the component.

For set value in local-storage we have use set function with name & it’s value like below code.


For get that value from the local-storage using get method & pass the name of the field.


For remove that value form the local-storage Remove method is their. pass name of the field.


Also attached below video to display how it work.

In template file you can write below code to get local-storage value.

<a (click)="getlocalstorage()">Get Local Storage value</a>
Local Storage Vale {{localstorage}}

When you click on the “Get Local Storage value” it display value which we have set.

Output of localstorage

Using above 3 method you can work easily with local-store getting,setting & removing the filed in any component.

Spread the love