Implementing Cookie Consent Policy in Angular: A Complete Guide

Abhinav Akhil
4 min readDec 6, 2022

--

If you run a website that collects data from users, you’re likely aware of the cookie consent policy. This legal requirement is designed to protect users’ privacy while they browse the internet. In Europe, it’s mandatory for websites to implement a proper cookie policy that notifies users that their session cookies are being stored for a better browsing experience. Essentially, you’re asking for the user’s consent before collecting any data, which can be done through a variety of methods, such as a popup or banner. In this blog, I’ll guide you through implementing a cookie consent policy in your Angular application to ensure compliance with data privacy regulations like GDPR.

In this tutorial, we will be utilizing the ngx-cookieconsent package to implement a cookie consent policy in your Angular application.So let's get started

  1. Open your terminal and run the below command:
npm install --save cookieconsent

this will install the Cookie Consent dependency:

2. Now install ngx-cookieconsent via:

npm install --save ngx-cookieconsent

We need to add cookieconsent listed as global library, for that we have to add below lines to the angular.json file.

"scripts": [
"node_modules/cookieconsent/build/cookieconsent.min.js"
],

"styles": [
"node_modules/cookieconsent/build/cookieconsent.min.css"
],

3. Next we need to add the following to the app.module.ts (main module)

Import these modules:

import {NgcCookieConsentModule, NgcCookieConsentConfig} from 'ngx-cookieconsent';

Cookie consent configurations, using this we can configure the look and feel of the cookie consent banner.

const cookieConfig:NgcCookieConsentConfig = {
cookie: {
domain: 'localhost' // or 'your.domain.com' // it is mandatory to set a domain, for cookies to work properly (see https://goo.gl/S2Hy2A)
},
palette: {
popup: {
background: '#000'
},
button: {
background: '#f1d600'
}
},
theme: 'edgeless',
type: 'opt-out'
};

Add this to the imports Array in ngModule

imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...]

The app module full code now looks like this:

import {NgcCookieConsentModule, NgcCookieConsentConfig} from 'ngx-cookieconsent';

const cookieConfig:NgcCookieConsentConfig = {
cookie: {
domain: 'localhost' // or 'your.domain.com' // it is mandatory to set a domain, for cookies to work properly (see https://goo.gl/S2Hy2A)
},
palette: {
popup: {
background: '#000'
},
button: {
background: '#f1d600'
}
},
theme: 'edgeless',
type: 'opt-out'
};


@NgModule({
declarations: [AppComponent, ...],
imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...],
bootstrap: [AppComponent]
})
export class AppModule {
}

Now your app is ready to use cookie consent throughout the application. It’s time to decide the place where you want to show the cookie. Ideally, we do it in the app component but feel free to experiment as per your requirement.

4. In app.component.ts inject the service into the constructor

private cookieService: NgcCookieConsentService

only doing this will make the cookie consent work for you but if want to customize more, you can do that as well.

Full code of app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { NgcCookieConsentService } from 'ngx-cookieconsent';
import { Subscription } from 'rxjs';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

//keep refs to subscriptions to be able to unsubscribe later
private popupOpenSubscription!: Subscription;
private popupCloseSubscription!: Subscription;
private initializingSubscription!: Subscription;
private initializedSubscription!: Subscription;
private initializationErrorSubscription!: Subscription;
private statusChangeSubscription!: Subscription;
private revokeChoiceSubscription!: Subscription;
private noCookieLawSubscription!: Subscription;

constructor(private cookieService: NgcCookieConsentService){}

ngOnInit() {
// subscribe to cookieconsent observables to react to main events
this.popupOpenSubscription = this.cookieService.popupOpen$.subscribe(
() => {
// you can use this.cookieService.getConfig() to do stuff...
});

this.popupCloseSubscription = this.cookieService.popupClose$.subscribe(
() => {
// you can use this.cookieService.getConfig() to do stuff...
});

this.initializingSubscription = this.cookieService.initializing$.subscribe(
(event: NgcInitializingEvent) => {
// the cookieconsent is initilializing... Not yet safe to call methods like `NgcCookieConsentService.hasAnswered()`
console.log(`initializing: ${JSON.stringify(event)}`);
});

this.initializedSubscription = this.cookieService.initialized$.subscribe(
() => {
// the cookieconsent has been successfully initialized.
// It's now safe to use methods on NgcCookieConsentService that require it, like `hasAnswered()` for eg...
console.log(`initialized: ${JSON.stringify(event)}`);
});

this.initializationErrorSubscription = this.cookieService.initializationError$.subscribe(
(event: NgcInitializationErrorEvent) => {
// the cookieconsent has failed to initialize...
console.log(`initializationError: ${JSON.stringify(event.error?.message)}`);
});

this.statusChangeSubscription = this.cookieService.statusChange$.subscribe(
(event: NgcStatusChangeEvent) => {
// you can use this.cookieService.getConfig() to do stuff...
});

this.revokeChoiceSubscription = this.cookieService.revokeChoice$.subscribe(
() => {
// you can use this.cookieService.getConfig() to do stuff...
});

this.noCookieLawSubscription = this.cookieService.noCookieLaw$.subscribe(
(event: NgcNoCookieLawEvent) => {
// you can use this.cookieService.getConfig() to do stuff...
});
}

ngOnDestroy() {
// unsubscribe to cookieconsent observables to prevent memory leaks
this.popupOpenSubscription.unsubscribe();
this.popupCloseSubscription.unsubscribe();
this.initializingSubscription.unsubscribe();
this.initializedSubscription.unsubscribe();
this.initializationErrorSubscription.unsubscribe();
this.statusChangeSubscription.unsubscribe();
this.revokeChoiceSubscription.unsubscribe();
this.noCookieLawSubscription.unsubscribe();
}
}

Congrats, Your cookie consent app is ready to launch now.

If you want to customize the banner, you can have a look at this: https://tinesoft.github.io/ngx-cookieconsent/home.

They have different types of customization available like the position of the cookie banner, custom text, color of the banner, etc.

Now that you’ve learned how to implement a cookie consent policy in your Angular application using ngx-cookieconsent, you’re one step closer to ensuring your website is compliant with data privacy regulations. I hope this article has been informative and helpful, and that you feel more confident in your ability to protect user privacy. As always, keep learning and stay up to date with the latest web development trends and best practices.

Thanks for reading!👋

--

--