Cookie set, read and delete in Angular 12+

In these article I have discuss about how to store cookie in browser in angular application How to set, read and delete cookie for the application.
First we need know what is cookie.
Cookies are small packages of information that are typically stored by your browser used in website for some information filter.

For cookie store we used package called “ngx-cookie-service”. To install run below code

npm install ngx-cookie-service --save

After installing package we need to added in the app.module.ts to use. Display in below code how to import service.

import { CookieService } from 'ngx-cookie-service';

After import service we can you in our component to set cookie display in below code it display how to set cookie in angular application

import { Component, VERSION } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
export class AppComponent {
  cookieValue: any;

  constructor(private cookieService: CookieService) {
    this.cookieService.set('Test', 'Hello World');
    this.cookieValue = this.cookieService.get('Test');

To set cookie we used set method. it contains two parameter 1) for name of cookie 2) Value of that cookie. In our example “Test” is cookie name and “Hello World” is the value of the cookie display in below code.

this.cookieService.set('Test', 'Hello World');

To get cookie we used “get” method and pass one parameter called name of the cookie. In below example “Test” is name of the cookie


Below is the example for the getall cookie, delete single cookie and deleteall cookie.

const allCookies: {} = this.cookieService.getAll(); // get all cookies

this.cookieService.delete('Test'); // delete Test cookie from the browser

this.cookieService.deleteAll(); //Deletes all cookies that can currently be accessed

Display in below screenshot Output of the above code.

Spread the love