🍪Cookie Management🥠 in Angular With ngx-cookie-service

If you want an easy way to manage browser cookies in your Angular project, then ngx-cookie-service may be the solution for you:

https://www.npmjs.com/package/ngx-cookie-service

This package includes and API that lets you get, set, and delete cookies. Today we will make an email subscription sign-up form to demonstrate this tool and set a simple cookie.

Procedure

First let’s make sure we have the latest Node and npm installed on our system. Download them here:

Next we’ll set up our Angular project. Install the Angular CLI tool:

npm install -g @angular/cli

Generate a new project:

ng new cookies

Change to the directory of the newly-created project:

cd cookies

Add Angular Material:

ng add @angular/material

Install ngx-cookie-service:

npm install ngx-cookie-service --save

Run the local dev server:

ng serve

Check localhost:4200 in your browser:

localhost:4200

Let’s replace the default HTML with an Angular material form. Here we will make a simple input and submit button to subscribe to an email list:

app.component.html

<div class="container">
  <h1>Subscribe</h1>
  <p>Get updates in your inbox</p>
  <mat-form-field appearance="fill">
    <mat-label>Email</mat-label>
    <input type="email" [formControl]="email" matInput />
  </mat-form-field>
  <button mat-raised-button color="accent" (click)="subscribe()">
    Subscribe
  </button>
</div>

Don’t forget the styles:

app.component.scss

.container {
  display: flex;
  flex-direction: column;
  width: 400px;
  align-items: center;
  margin: auto;
  padding-top: 5rem;
}

Now add the cookie service to our module in the providers list:

app.module.ts

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { CookieService } from 'ngx-cookie-service';
import { AppComponent } from './app.component';

const MATERIAL = [
  MatFormFieldModule,
  MatInputModule,
  MatButtonModule,
  MatSnackBarModule,
];

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    ...MATERIAL,
  ],
  providers: [CookieService],
  bootstrap: [AppComponent],
})
export class AppModule {}

We will inject the cookie service into our component. The subscribe() method will be triggered upon clicking the Subscribe button, which sets the cookie featuring our email address.

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public email = new FormControl('');

  constructor(
    private cookieService: CookieService,
    private snackBar: MatSnackBar
  ) {}

  public openSnackBar(): void {
    this.snackBar.open('Submitted', 'CLOSE');
  }

  public subscribe(): void {
    this.cookieService.set('Email', `${this.email.value}`);
    this.openSnackBar();
  }
}

To test this feature, we’ll add an email address and click Subscribe:

If we look at our Developer Tools in our browser settings and go to the Application tab, we can see our saved cookie:

That’s the most basic useage of ngx-cookie-service. I hope this tutorial was useful and fun!

Feature Image by Suzy Hazelwood from Pexels

Latest Posts

Leave a comment