0

I want to clear Localstorage data on browser back button click. But how to detect browser back button click in Angular2. I am not getting any exact solution. Can anyone please tell me how to do this?

5
  • There is a difference if you navigate back within the page (undo a route navigation) and navigating back to a different page. What are you interested in? "I am not getting any exact solution." Your question should demonstrate what you tried and why you didn't get the expected result and what the expected result is. Commented Sep 11, 2017 at 9:56
  • Browser back button means obviously it ll redirect to a different page.And I am not getting any solution for that.@GünterZöchbauer Commented Sep 11, 2017 at 9:59
  • That's not obvious at all. If you navigate between angular routes and then back, you're always on the same page, until you go as far back using the back button until you reached the initial state and then the next back button click navigates away from the application and to the previous application or page. Commented Sep 11, 2017 at 10:03
  • I think what you're looking for is stackoverflow.com/questions/37642589/… (see also stackoverflow.com/questions/40468267/…) Commented Sep 11, 2017 at 10:04
  • @Dheeraj Kumar 's answer is working for me.Thank you for your time.@GünterZöchbaue Commented Sep 11, 2017 at 10:08

1 Answer 1

1

You can use ngOnDestroy method of components which is part of component life cycle.

This component is called whenever component is destroyed.

What you can do is create a service where your logic to clean localstorage will be written.

Call this service on ngOnDestroy method of your component.

remember to import {OnDestroy} from '@angular/core' and add OnDestroy to the implements section of your Class definition

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

I doubt ngOnDestroy is called when the back button navigates away from the application.
It is sir. As soon as current application is closed or navigated to another application.
I'm sure it isn't, because this is the same for the application as closing the tab where ngOnDestroy also isn't called. I don't know how to reproduce in Plunker though.
Thank you so much @Dheeraj Kumar.It is working for me.You saved my day.:):)
@ananya I am glad it helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.