Transfer Data Among Different tabs in Angular
I am pretty sure that you already know how to transfer data in angular between two components because there is some perfect article about them such as these two:
Describing the Problem
There is a problem in transferring data between tabs, which is not mentioned yet, so I decided to write about it. When we are redirecting to a new tab in the browser from somewhere in our application, it looks like that we have opened a new instance of our application. Based on the fact that all of them using a new service and pipeline, we don’t have any access to old tab values, so we can’t use any of the previous methods.
What is the solution?
Let solve this issue with a simple approach by using Localstorage events.
For example, we want to transfer data from component A to component B in another tab of our browser.
Step 1: Add a function to handle the actions you want to do with the new value in component B like this:
Step 2: Add a function listener to handle the raising events of Localstorage:
Step 3: We should bind these two together and add an event listener by these commands. The first line is binding our function listener to our action function and the second line is adding an event listener to our local storage.
Notice: Whenever we use windows.addEventListener we should be careful to destroy it also or it will become a new problem for our application.
Step 4: I prefer to implement OnDestroy in my classes to remove the event listener like below but you can use whatever you want.
As you can see, I just passed my ‘funcListener’ to the removeEventListener to stop checking the local storage activities after I destroyed my components.
Final Step: the final step is just to set or remove something from your local storage by one of these two commands.
Conclusion: As simple as that we can share the data between two Tabs in our browser. Please support me with your claps.
What tips do you have for writing more practical functions?