Site icon Learn Web Development & Programming, Artificial Intelligence, WordPress, Shopify Articles

How to use cookies in angular

cookies in angular

What is Cookies in Angular?

Cookies are small packages of information that can be temporarily stored/saved by your browser and websites which are using cookies for multiple things.

Cookies are used in multiple requests and browser sessions and can store your account information used by authentication for example.

Also Read: Transpilation in Angular

Size of Cookies

They are often not more than a few kilobytes per cookie.

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

app.module.ts file

Also Read: Angular Online Quiz Test

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,

app.component.ts file

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

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

Set, get and getAll Cookies

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

Delete and Delete All Cookies

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

app.component.html file

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

Method of Cookies in Angular

Conclusion

Thank you for reading How to use cookies in angular article. Hope I was able to help someone out. If you have any questions feel free to ask anything on the comment section. Cheers!!.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit a paid service request

Exit mobile version