How To Save And Get Values From Cookies Using Angular

In this article, we will learn how to save and get cookies using Angular v2.
 
Procedure to save a value in cookies using Angular version 2
 
In the following code, we pass three parameters:
  1. name - the name of the cookie (that you want to create)
  2. value - the value you want to save in the cookie
  3. days - expiry days for your cookie
This is a simple live example of how to use a cookie in your application,
  1. GetNames() {  
  2.     var strVal = this.readCookie("Angular2_demo");  
  3.     var name = this.Registration.Address  
  4.     if (strVal == name) {  
  5.         alert("hi i am " + name);  
  6.     }  
  7. };  
  8. savecookies() {  
  9.     this.createCookie("Angular2_demo"this.Registration.Name, 7);  
  10. }  
  11. createCookie(name: string, value: string, days: number) {  
  12.     var expires = "";  
  13.     if (days) {  
  14.         var date = new Date();  
  15.         date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));  
  16.         expires = "; expires=" + date.toUTCString();  
  17.     }  
  18.     document.cookie = name + "=" + value + expires + "; path=/";  
  19. }  
  20. readCookie(name: string) {  
  21.     debugger;  
  22.     var nameEQ = name + "=";  
  23.     var ca = document.cookie.split(';');  
  24.     for (var i = 0; i < ca.length; i++) {  
  25.         var c = ca[i];  
  26.         while (c.charAt(0) == ' ') c = c.substring(1, c.length);  
  27.         if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);  
  28.     }  
  29.     return null;  
  30. }  
  31. eraseCookie(name: string) {  
  32.     this.createCookie(name, "", -1);  
  33. } < input type = "text"  
  34. class = "form-control"  
  35. id = "Name"  
  36. name = "Name" [(ngModel)] = "Registration.Name" (blur) = "savecookies()"  
  37. placeholder = "Enter Name" > < button type = "submit"  
  38. class = "btn" (click) = "GetNames()" > GetNames < /button>  
Ebook Download
View all
Learn
View all