Search code examples
angularbrowserback-button

How to detect browser back button click in Angular2


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?


Solution

  • 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.