Find out how to add functionality in your Angular 2 application that updates data in web storage based on your user's input.
- [Instructor] We set items in session storage using the set item method of the session storage property found on the browser's window object. Session storage is a built in browser global and no special angular code is needed to use this feature. In our application let's add functionality in our user list component that updates session storage with whatever text is typed into the filter input in our UI. This is done by adding a reference to the session storage property inside our on filter method in the component.
In our method we'll add a new line underneath the filter property. And we will reference the window.sessionStorage.setItem method. The set item method takes two arguments. The first argument is a string representing key for our data, in this case filter, and the second argument is the data itself. For us this is this.filter.
Session storage data is always stored as a string. In this case, our filter is already a string and we can pass it directly into the set item method. But for other data types like objects, or rays, and Booleans, you'll need to convert this data into a string type before sending it to session storage. You can use JSON stringify or a similar technique to convert non strings into strings. To do this, we'll create a new variable and we'll call it storagevalue, and we'll assign this variable to the result of JSON.stringify passing our filter into the meta.
In our set item method, instead of referencing the this.filter property, we'll reference the storage value instead. If we open our developer tools in Chrome and look at the Application tab, we can peek inside session storage and watch our new key value pair update in real time as the filter text changes.
- Overview of data storage options
- Saving and retrieving data from the browser
- Setting routes in the URL
- Using query strings and fragments instead of routes
- Saving and retrieving data from a server
- Working with user input
- Using JSONP instead of HTTP
- Why writing custom services is important
- Writing custom services for working with browsers and servers