DEV Community

Cover image for Angular : Add cookie consent in your angular project just in 5 minutes #trending
RajeshKumarYadav.com
RajeshKumarYadav.com

Posted on • Updated on • Originally published at developersdiscussion.com

Angular : Add cookie consent in your angular project just in 5 minutes #trending

Open your terminal and run below command -

npm install --save cookieconsent
Enter fullscreen mode Exit fullscreen mode

Now install ngx-cookieconsent via:

npm install --save ngx-cookieconsent
Enter fullscreen mode Exit fullscreen mode

Once installed you need to import the main module app.module.ts:

import {NgcCookieConsentModule} from 'ngx-cookieconsent';
Enter fullscreen mode Exit fullscreen mode

Add this import to imports of @NgModule on the same file app.module.ts

imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...], 
Enter fullscreen mode Exit fullscreen mode

After adding above import in @NgModule your code will look like this-

@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...],  
  bootstrap: [AppComponent]
})
Enter fullscreen mode Exit fullscreen mode

Now add below code in the same file app.module.ts -

CODE:

const cookieConfig:NgcCookieConsentConfig = {
  cookie: {
    domain: 'localhost' // or 'your.domain.com' 
  },
  palette: {
    popup: {
      background: '#000'
    },
    button: {
      background: '#f1d600'
    }
  },
  theme: 'edgeless',
  type: 'opt-out'
};
Enter fullscreen mode Exit fullscreen mode

Once you have done all above steps, your full code for cookie consent will look like this

app.module.ts

// ...
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 {
}
Enter fullscreen mode Exit fullscreen mode

where ... is your existing code.

Now your app module is ready to use cookie consent in your angular application.

Now open that component where you want to add this, in most of the cases any global component you can choose to call cookie consent on each page.

Here is how it works:

app.component.ts

import { Component, OnInit, OnDestroy } from "@angular/core";
import {
  NgcCookieConsentService,
  NgcNoCookieLawEvent,
  NgcInitializeEvent,
  NgcStatusChangeEvent,
} from "ngx-cookieconsent";
import { Subscription } from "rxjs";

import { RouterExtService } from "./services/routerurlstate.service";

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

  //keep refs to subscriptions to be able to unsubscribe later
  private popupOpenSubscription: Subscription;
  private popupCloseSubscription: Subscription;
  private initializeSubscription: Subscription;
  private statusChangeSubscription: Subscription;
  private revokeChoiceSubscription: Subscription;
  private noCookieLawSubscription: Subscription;

  constructor(
    private ccService: NgcCookieConsentService,
    private routerExtService: RouterExtService
  ) {
    console.log(this.routerExtService.getCurrentUrl());
    console.log(this.routerExtService.currentUrl);
  }

  handleClickSound() {
    let x = <HTMLVideoElement>document.getElementById("myAudio");
    x.play();
  }
  ngOnInit() {
    // subscribe to cookieconsent observables to react to main events
    this.popupOpenSubscription = this.ccService.popupOpen$.subscribe(() => {
      // you can use this.ccService.getConfig() to do stuff...
    });

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

    this.initializeSubscription = this.ccService.initialize$.subscribe(
      (event: NgcInitializeEvent) => {
        // you can use this.ccService.getConfig() to do stuff...
      }
    );

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

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

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

  ngOnDestroy() {
    // unsubscribe to cookieconsent observables to prevent memory leaks
    this.popupOpenSubscription.unsubscribe();
    this.popupCloseSubscription.unsubscribe();
    this.initializeSubscription.unsubscribe();
    this.statusChangeSubscription.unsubscribe();
    this.revokeChoiceSubscription.unsubscribe();
    this.noCookieLawSubscription.unsubscribe();
  }
}
Enter fullscreen mode Exit fullscreen mode

Then run ng server command and you will see cookie consent working on your page.

Extra Bits-

If you have multiple domain or you are testing on subdomain and then want to deploy to actual domain then in this case you can make the domain dynamic -

CODE:

 cookie: { domain: window.location.hostname, },
Enter fullscreen mode Exit fullscreen mode

Demo - https://rajeshkumaryadav.com

Buy Me A Coffee

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

Top comments (2)

Collapse
 
kwhjvdkamp profile image
Koen (K.W.H.J.) van der Kamp

As many of you (readers) know, recently Angular 16 came around! Libraries tagged as non-Ivy became deprecated with this new born.

This counts for ngx-cookieconsent also ! Count your blessings with Angular 15 wait till ngx-cookieconsent becomes Ivy-compliant!

github.com/tinesoft/ngx-cookiecons...

Collapse
 
manojbharti profile image
Manoj • Edited

What is the use of RouterExtService class?