Implementing Cookie Policy for an Angular App

So if you are living in Europe and/or working for a company that has the business in Europe, your life as a web developer is already quite messy thanks to Cookie Law and GDPR.
If you are building a web app, you need to keep in mind to implement a proper Cookie policy that tells your customer that you are storing their session cookies to give them the better web experience. You might also consider giving them opt-out or in more advanced case, explicit opt-in.

291641_cookie1
Copyright: Hrvoje Jurisic

Moreover, this can be always more irritating, as this is not your primary use case on the website. Thanks to some awesome people and awesome libraries such as CookieConsent, the life of a normal web developer is made quite easy.

In today's blogpost, I am going to write about how to implement cookie banner in Angular Application using cookie-consent.

Cookie consent although has made our lives really really simple, but to correctly implement it in Angular application is a little bit tricky. Specially when you want to use Localisation and envrionment variables for the dynamic links. Of course, there is a plugin for this (Isn't there always a plugin?) But as I am gaining more and more experience in web development, my will to use a third party plugin is going down and down.

So back to our topic, how to implement cookie-consent in an Angular app?
Quite simple. First, take these two references in your index.html file -

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.css" />
  <script src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.js"></script>

These will download relevant javascript and css files from CDN at the time of loading website. Alternatively, you can also download them, and host them inside your application.

Then go to your app.component.ts and write following lines of code inside ngOnInit function -

       let cc = window as any;
       cc.cookieconsent.initialise({
         palette: {
           popup: {
             background: "#164969"
           },
           button: {
             background: "#ffe000",
             text: "#164969"
           }
         },
         theme: "classic",
         content: {
           message: this.cookieMessage,
           dismiss: this.cookieDismiss,
           link: this.cookieLinkText,
           href: environment.Frontend + "/dataprivacy" 
         }
       });

Using this, you can localise your message string, and even add environment specific link for more information hyperlink.
You can further customise it with your own styles, text, and everything you wish to do.
The final result is, something as beautiful as this -
291648_Sketch

That's it. You can make your Angular application Cookie Law compliance in less then 15 minutes.
Happy Coding. :)


comments powered by Disqus