All Projects → tinesoft → Ngx Cookieconsent

tinesoft / Ngx Cookieconsent

Licence: mit
Cookie 🍪 Consent module for Angular.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Ngx Cookieconsent

Nookies
🍪 A set of cookie helpers for Next.js
Stars: ✭ 1,035 (+762.5%)
Mutual labels:  hacktoberfest, cookie
Simple Cookie Choices
A simple cookie choices thought to the GDPR rules 🔒🍪
Stars: ✭ 12 (-90%)
Mutual labels:  law, cookie
Pg ha migrations
Enforces DDL/migration safety in Ruby on Rails project with an emphasis on explicitly choosing trade-offs and avoiding unnecessary magic.
Stars: ✭ 119 (-0.83%)
Mutual labels:  hacktoberfest
Newsboat
An RSS/Atom feed reader for text terminals
Stars: ✭ 1,798 (+1398.33%)
Mutual labels:  hacktoberfest
Sudoku Solver
GUI Sudoku Solver using Pygame
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest
Stryker4s
Mutation testing for Scala. Work in progress...
Stars: ✭ 118 (-1.67%)
Mutual labels:  hacktoberfest
Angular Open Source Starter
This is a starter project for creating open-source libraries for Angular. It is a full fledged Angular workspace with demo application and easy library addition. It is designed to be used for open-sourcing libraries on Github and has everything you'd need ready for CI, code coverage, SSR testing, StackBlitz demo deployment and more.
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest
Unshort.link
Prevent short link services from tracking you by unshortening the urls for your
Stars: ✭ 119 (-0.83%)
Mutual labels:  hacktoberfest
Axolotl
A Signal compatible cross plattform client written in Go and Vuejs
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest
Pythonalgorithms
All Algorithms implemented in Python 3
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest
Dev Folio
🔥 A collection of Free Portfolio templates for developers.
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest
Tsuru Dashboard
Web dashboard for tsuru PaaS.
Stars: ✭ 119 (-0.83%)
Mutual labels:  hacktoberfest
Editorconfig Checker
A tool to verify that your files are in harmony with your .editorconfig
Stars: ✭ 119 (-0.83%)
Mutual labels:  hacktoberfest
Freud
Powerful, efficient particle trajectory analysis in scientific Python.
Stars: ✭ 118 (-1.67%)
Mutual labels:  hacktoberfest
Lumos
💡 A light Swift wrapper around Objective-C Runtime
Stars: ✭ 119 (-0.83%)
Mutual labels:  hacktoberfest
Customizer
Kanboard - Customizer adds GUI for logo, favicon and themes
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest
Useful Dev Tools
⭐️ A list with useful tools that help many Developers. Hacktoberfest ⭐️
Stars: ✭ 119 (-0.83%)
Mutual labels:  hacktoberfest
Git Url Parse
✌️ A high level git url parser for common git providers.
Stars: ✭ 119 (-0.83%)
Mutual labels:  hacktoberfest
Monk gui
A Graphical user Interface for deep learning and computer vision over Monk Libraries
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest
Vue Select Image
✅ Vue 2.x component for selecting image from list
Stars: ✭ 120 (+0%)
Mutual labels:  hacktoberfest

ngx-cookieconsent - Cookie Consent module for Angular.

npm version Build Status Coverage Status dependency Status devDependency Status Greenkeeper Badge

Demo

View the module in action at https://tinesoft.github.io/ngx-cookieconsent

Dependencies

  • Angular (requires Angular 6+, v1.1.0 is the latest version for Angular < 6 )
  • Cookie Consent (requires Cookie Consent 3 or higher, tested with 3.1.0)

Installation

Install above dependencies via npm. In particular for Cookie Consent:

npm install --save cookieconsent

Now install ngx-cookieconsent via:

npm install --save ngx-cookieconsent

Angular-CLI

Note: If you are using angular-cli to build your app, make sure that cookieconsent is properly listed as a global library, and as global style.

To do so, edit your angular-cli.json as such:

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

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

SystemJS

Note:If you are using SystemJS, you should adjust your configuration to point to the UMD bundle. In your systemjs config file, map needs to tell the System loader where to look for ngx-cookieconsent:

map: {
  'ngx-cookieconsent': 'node_modules/ngx-cookieconsent/bundles/ngx-cookieconsent.umd.js',
}

In your systemjs config file, meta needs to tell the System loader how to load cookieconsent:

    meta: {
    './node_modules/cookieconsent/build/cookieconsent.min.js': {
            format: 'amd'
        }
    }

In your index.html file, add script and link tags to load cookieconsent globally:

    <!-- 1. Configure SystemJS -->
    <script src="system.config.js"></script>
    <!-- 2. Add cookieconsent dependency-->
    <link rel="stylesheet" type="text/css" href="node_modules/cookieconsent/build/cookieconsent.min.css"/>
    <script src="node_modules/cookieconsent/build/cookieconsent.min.js"></script>

Once installed you need to import the main module:

import {NgcCookieConsentModule} from 'ngx-cookieconsent';

The only remaining part is to list the imported module in your application module. The exact method will be slightly different for the root (top-level) module for which you should end up with the code similar to (notice NgcCookieConsentModule.forRoot()):

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

Other modules in your application can simply import NgcCookieConsentModule:

import {NgcCookieConsentModule} from 'ngx-cookieconsent';

@NgModule({
  declarations: [OtherComponent, ...],
  imports: [NgcCookieConsentModule, ...], 
})
export class OtherModule {
}

Usage

Inject the NgcCookieContentService in your main component (i.e. AppComponent) to show the cookie consent popup after the component is loaded. You don't need to explicitly call its init() method (done automatically when the service's constructor gets called upon instantiation By Angular).

Also, you can use the injected NgcCookieContentService to update the config (using init()), subscribe to events and do stuff like disabling cookies or other.

Here is how it works:

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 initializeSubscription: Subscription;
  private statusChangeSubscription: Subscription;
  private revokeChoiceSubscription: Subscription;
  private noCookieLawSubscription: Subscription;

  constructor(private ccService: NgcCookieConsentService){}

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

See Cookie Consent Documentation to see more about how to customize the UI or interact with user interactions.

I18n Support

Messages displayed in the Cookie Consent Bar can easily be translated, using libraries like ngx-translate. Basically this involved the following steps (using ngx-translate + Anglar CLI):

  • Install and configure ngx-translate

  • Provide the translation JSON files in src/assets/, for e.g: en.json, fr.json, ...

{
    "cookie": {
        "header": "Cookies used on the website!",
        "message": "This website uses cookies to ensure you get the best experience on our website.",
        "dismiss": "Got it!",
        "allow": "Allow cookies",
        "deny": "Decline",
        "link": "Learn more",
        "policy": "Cookie Policy"
    }
}

Note: see content-options.ts for complete list of messages that can be translated.

  • Configure your main component AppComponent
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

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

  constructor(private ccService: NgcCookieConsentService, private translateService:TranslateService) {
  }

  ngOnInit() {
    // Support for translated cookies messages
    this.translateService.addLangs(['en', 'fr']);
    this.translateService.setDefaultLang('en');

    const browserLang = this.translateService.getBrowserLang();
    this.translateService.use(browserLang.match(/en|fr/) ? browserLang : 'en');

    this.translateService//
      .get(['cookie.header', 'cookie.message', 'cookie.dismiss', 'cookie.allow', 'cookie.deny', 'cookie.link', 'cookie.policy'])
      .subscribe(data => {

        this.ccService.getConfig().content = this.ccService.getConfig().content || {} ;
        // Override default messages with the translated ones
        this.ccService.getConfig().content.header = data['cookie.header'];
        this.ccService.getConfig().content.message = data['cookie.message'];
        this.ccService.getConfig().content.dismiss = data['cookie.dismiss'];
        this.ccService.getConfig().content.allow = data['cookie.allow'];
        this.ccService.getConfig().content.deny = data['cookie.deny'];
        this.ccService.getConfig().content.link = data['cookie.link'];
        this.ccService.getConfig().content.policy = data['cookie.policy'];

        this.ccService.destroy(); // remove previous cookie bar (with default messages)
        this.ccService.init(this.ccService.getConfig()); // update config with translated messages
      });
  }
}

Custom Layout Support

Cookie Consent supports custom layouts, and so does ngx-cookieconsent. So if your are not happy with the default appearance of the cookie bar, you can totally customize it to better suit your needs. This involves overriding a few options:

Here is a example of a custom layout, that is inspired from the default 'basic' layout , but simply changes the message and links that are displayed in the bar.

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

const cookieConfig:NgcCookieConsentConfig = {
  cookie: {
    domain: 'localhost'// it is recommended to set your domain, for cookies to work properly
  },
  palette: {
    popup: {
      background: '#000'
    },
    button: {
      background: '#f1d600'
    }
  },
  theme: 'edgeless',
  type: 'opt-out',
  layout: 'my-custom-layout',
  layouts: {
    "my-custom-layout": '{{messagelink}}{{compliance}}'
  },
  elements:{
    messagelink: `
    <span id="cookieconsent:desc" class="cc-message">{{message}} 
      <a aria-label="learn more about cookies" tabindex="0" class="cc-link" href="{{cookiePolicyHref}}" target="_blank">{{cookiePolicyLink}}</a>, 
      <a aria-label="learn more about our privacy policy" tabindex="1" class="cc-link" href="{{privacyPolicyHref}}" target="_blank">{{privacyPolicyLink}}</a> and our 
      <a aria-label="learn more about our terms of service" tabindex="2" class="cc-link" href="{{tosHref}}" target="_blank">{{tosLink}}</a>
    </span>
    `,
  },
  content:{
    message: 'By using our site, you acknowledge that you have read and understand our ',
    
    cookiePolicyLink: 'Cookie Policy',
    cookiePolicyHref: 'https://cookie.com',

    privacyPolicyLink: 'Privacy Policy',
    privacyPolicyHref: 'https://privacy.com',

    tosLink: 'Terms of Service',
    tosHref: 'https://tos.com',
  }
};


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

Credits

ngx-cookieconsent is built upon Cookie Consent, by Osano

License

Copyright (c) 2020 Tine Kondo. Licensed under the MIT License (MIT)

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].