Skip to content

Static Class (Minimum Example)

Richard Natal edited this page Sep 27, 2017 · 1 revision
npm install -g @angular/cli
ng new ng2-cookies-test
cd ng2-cookies-test
npm install --save ng2-cookies
code .
ng serve

Edit the app.component.html to be like this:

<h1>
  {{title}}
</h1>

<table>
  <thead>
    <tr>
      <td colspan="2">Cookies:</td>
    </tr>
    <tr>
      <th>Name</th>
      <th>Value</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let cookie of keys">
      <td>{{cookie}}</td>
      <td>{{cookies[cookie]}}</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>
        <label for="iName">Name:</label>
        <span><input type="text" id="iName" [(ngModel)]="cName"></span>
      </td>
      <td>
        Value:
        <span><input type="text" [(ngModel)]="cValue"></span>
        <input type="button" value="Add" (click)="addCookie(cName, cValue)">
      </td>
    </tr>
    <tr>
      <td colspan="2">
        Name:
        <span><input type="text" [(ngModel)]="rName"></span>
        <input type="button" value="Remove" (click)="removeCookie(rName)">
        <input type="button" value="Remove All" (click)="removeAll()">
      </td>
    </tr>
    <tr>
      <td colspan="2">
        Name:
        <span><input type="text" [(ngModel)]="checkName"></span>
        <input type="button" value="Check" (click)="checkCookie(checkName)">
      </td>
    </tr>
  </tfoot>
</table>

Edit the app.component.ts to be like that:

import { Component } from '@angular/core';
import { Cookie } from 'ng2-cookies';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  cookies: Object;
  keys: Array<string>;
  cName: string;
  cValue: string;
  rName: string;
  checkName: string;

  constructor() {
    this.update();
    console.log(this.cookies);
  }
  update() {
    this.cookies = Cookie.getAll();
    this.keys = Object.keys(this.cookies);
  }
  addCookie(cName: string, cValue: string) {
    console.log('Adding: ', cName, cValue);
    Cookie.set(cName, cValue);
    this.update();
  }
  removeCookie(rName: string) {
    console.log('Removing: ', rName);
    Cookie.delete(rName);
    this.update();
  }
  removeAll() {
    console.log('Removing all cookies');
    Cookie.deleteAll();
    this.update();
  }
  checkCookie() {
    console.log('Checking: ', this.checkName);
    console.log(Cookie.check(this.checkName));
    window.alert('Check cookie ' + this.checkName + ' returned ' + Cookie.check(this.checkName));
  }
}

Open your browser and navigate to http://localhost:4200/

Clone this wiki locally