-1


I'm developing a form and I'm using Angular reactive forms.
I need save the form values when the user reload the page, 'cause I have a translate service, and this service, reload the page when the user change the language.

How can I save user form values, when he change the language?

  • How to save or where to save? – riorudo Jun 17 '19 at 19:13
  • You may want a pipe that takes the entire FormGroup to translate the language and replace the values. I think we need more details though. – Ben Racicot Jun 17 '19 at 19:15
  • There are many ways to do it. Do you need it to persist in a database? Then use a service call to store it. Do you just want it to persist on the user's computer? Then use `localStorage`. Page refreshes usually mean the end of an Angular app's state such that it must calculate it all again. – amphetamachine Jun 17 '19 at 19:25
  • Yes, I know that refresh an Angular page is very ugly, but, the implementation of the translate service was not I that have developed.. So, I was looking for a basic implementation.. Thanks to everyone that have answered my question. – Martin Ruediger Jun 18 '19 at 10:43

2 Answers2

2

I'm not sure which library you are using for the translation and why it works like that,but I will try to answer your question anyway.

If you are interested to store form values whenever the language is changed, you can simply hook into the language change event.

For instance with ngx-translate you can simply hook to the onLangChange event.

onLangChange.subscribe((event: LangChangeEvent) => {
  const formValue = this.form.value
  // Persist form value into the localStorage
});

Another option is to simply persist your form values to the localStorage whenever a change is made to the form. Like (DerrickF suggested) That way you will always have the latest form value:

  this.form.valueChanges.subscribe(formValue=> // Persist to local storage)

and you can simply load them from localStorage and set the form value with

this.form.setValue(**yourPersistedFormValue**)
Omri L
  • 739
  • 4
  • 12
  • Exactly, I'm using ngx-translate.. As I said in the comment above, I know that refresh an Angular page is very ugly, but, the implementation of the translate service was not I that have developed.. So, I was looking for a basic implementation.. Thanks for your answer, works very well!! – Martin Ruediger Jun 18 '19 at 10:43
1

You can stringify the form values and save them to local storage, then get them back into the form if the app reloads.

// Set in local storage
localStorage.setItem(itemName, JSON.stringify(formValues)); 

// Retrieve data from localstorage 
formVals= JSON.parse(localStorage.getItem(itemName));
DerrickF
  • 682
  • 5
  • 9