Angular : Add cookie consent in your angular project just in 5 minutes #trending
Tags: angular, node, typescript, javascript
Published: 2021-06-18 05:26:53

Open your terminal and run below command -
```javascript
npm install --save cookieconsent
```

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

Once installed you need to import the main module `app.module.ts`:
```javascript
import {NgcCookieConsentModule} from 'ngx-cookieconsent';
```

Add this import to imports of `@NgModule` on the same file `app.module.ts`
```javascript
imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...], 
```

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

```javascript
@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgcCookieConsentModule.forRoot(cookieConfig), ...],  
  bootstrap: [AppComponent]
})
```

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

CODE:

```javascript
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`
```javascript
// ...
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

```javascript
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:

```javascript
 cookie: { domain: window.location.hostname, },
```

Demo - [https://rajeshkumaryadav.com](https://rajeshkumaryadav.com)

<a href="https://www.buymeacoffee.com/rkycom" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

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](https://www.linkedin.com/in/www-rajeshkumaryadav-com/) and [Twitter](https://twitter.com/rky_com).