What is Cookies in Angular?

Cookies are small packages of information that can be temporarily stored/saved by your browser and websites that use cookies for multiple things. Cookies are used in multiple requests and browser sessions and can store your account information used by authentication for example.

 

How to install Cookies Dependency

We already have an NPM package for Angular called ‘ngx-cookie-service‘ that can be used for cookie use. Let’s install the cookies dependency using the below command:

After installing the cookies dependency, we have to import the CookieService inside one of our modules and add them as a provider. Please refer the below example code:

How to use Cookies in Angular

Now we will use our AppComponent and use the set, get, and delete method of the CookieService. In the below example code,

we import the CookieService inside the app.component.ts file.

Next step, we will inject this service into the parameters of the constructor and set the private variable.

Set, get, and getAll Cookies

In the first line, we are using the set function to set the new cookie value with the name. In the second line, we are using the get function to get the cookie value with the cookie name.

Delete and Delete All Cookies

In the first line, we are using the delete function to delete the single cookie value with the name. In the second line, we are using the deleteAll function to delete all cookie values with a single click.

We use the below code to display the output in the browser and trigger the set Cookies, Delete, and Delete All functions.

Method of Cookies in Angular

  • Check: Used to check whether cookies exit or not
  • Set: Used to set the value in cookies with the name
  • Get: Used to return the single value of stored cookies name
  • Get All: Used to return a value object of all cookies
  • Delete: Used to delete the value of the single cookie with the given name
  • Delete All: Used to delete all the cookies

Leave a Comment