How to add cookie consent in your angular project just in 5 minutes?

Get support on Angular & Typescript related technology.
Post Reply
admin
Site Admin
Posts: 44

How to add cookie consent in your angular project just in 5 minutes?

Post by admin » Thu May 21, 2020 1:01 am

Image

Open your terminal and run below command -

Code: Select all

npm install --save cookieconsent
Now install ngx-cookieconsent via:

Code: Select all

npm install --save ngx-cookieconsent
Once installed you need to import the main module app.module.ts:

Code: Select all

import {NgcCookieConsentModule} from 'ngx-cookieconsent';
Add this import to imports of @NgModule on the same file app.module.ts

Code: Select all

imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...], 
After adding above import in @NgModule your code will look like this-

Code: Select all

@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...],  
  bootstrap: [AppComponent]
})
Now add below code in the same file app.module.ts -

Code: Select all

const cookieConfig:NgcCookieConsentConfig = {
  cookie: {
    domain: 'localhost' // or 'your.domain.com' 
  },
  palette: {
    popup: {
      background: '#000'
    },
    button: {
      background: '#f1d600'
    }
  },
  theme: 'edgeless',
  type: 'opt-out'
};
Once you have done all above steps, your full code for cookie consent will look like this
app.module.ts

Code: Select all

// ...
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 {
}
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

Code: Select all

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();
  }
}
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: Select all

 cookie: {
    domain: window.location.hostname,
  },
Demo - https://rajeshkumaryadav.com

Post Reply