0

I'm setting localStorage inside ngOnDestroy and retriving it in ngOnInit. It works when user navigates to other view but it's not setting the localStorage on exiting the browser.

//currentnote is my variable which is connected with 2 way binding with the input field
ngOnInit() {
        let unsavedNote = localStorage.getItem('unsavedNote');
        if(unsavedNote) {
          this.currentnote=unsavedNote;
        }
    } 

ngOnDestroy(){`enter code here`
      if(this.currentnote && this.currentnote!=""){
        localStorage.setItem('unsavedNote', this.currentnote);
      }
    }
  • It should save between closing and opening, so it could be an issue with the your browser clearing it, like in this [case](https://stackoverflow.com/questions/51498749/localstorage-resets-after-close-browser) where it was needed to unselect "Delete browsing history on exit" – blapaz May 23 '19 at 20:35
  • @blapaz here is the more details : it saves data in these cases: 1. input data -> move to different view -> again come back to the view -> closes the browser without changing data 2. input data -> move to different view -> closes the browser ------ WHILE it remembers the old data when input data -> move to different view -> again come back to the view and changes the data -> closes the browser – Bhadresh Dudhat May 23 '19 at 21:01

2 Answers2

0

Based on what you describe in your comment, this is expected behavior. OnDestroy() is only called when switching between components. You can look at this question for more on when it is called.

In reference to the cases in your comment:

  1. works because it saves when you move to the other view.

  2. works for the same reason as case 1.

  3. shows old data for the reason above. The only time data is being saved is when you switch the view, after that you are just closing the browser so OnDestroy() is not called, and neither is your localstorage save.

Your better approach would be to have a save button or something to invoke the localstorage save. If you want it to be automatic then you would have to save on blur of the input field or on keystrokes, but this would probably get messy fast.

blapaz
  • 334
  • 2
  • 11
0

you can add beforeunload HostListener in your component and do the same logic like ngOnDestroy:

@HostListener('window:beforeunload')
onBeforeUnload() {
    if(this.currentnote && this.currentnote!=""){
        localStorage.setItem('unsavedNote', this.currentnote);
    }
}

see answer Is there any lifecycle hook like window.onbeforeunload in Angular2?

Floyd
  • 367
  • 2
  • 5