How To Set And Get Cookies In Angular With Example

How To Set And Get Cookies In Angular With Example?

You can use the next-cookie-service package to set and get cookies in Angular. Here's an example,

1. First, install the ngx-cookie-service package using the following command.

npm install ngx-cookie-service --save

2. Import the CookieService from the ngx-cookie-service package in your component.

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

3. Create an instance of the CookieService in your constructor.

constructor(private cookieService: CookieService) { }

4. To set a cookie, use the set method of the CookieService.

this.cookieService.set('cookieName', 'cookieValue');

5. To get a cookie, use the get method of the CookieService.

const cookieValue = this.cookieService.get('cookieName');

Here's the complete code for setting and getting a cookie:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private cookieService: CookieService) {
    // Set cookie
    this.cookieService.set('cookieName', 'cookieValue');

    // Get cookie
    const cookieValue = this.cookieService.get('cookieName');
    console.log('Cookie value:', cookieValue);
  }
}

Note. Remember to import the CookieModule in your app.module.ts file after installing the package.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CookieModule } from 'ngx-cookie';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CookieModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I hope this helps. If this helps you, then share it with others.

Sharing is caring! :)