Home > front end >  How to retain values in angular forms
How to retain values in angular forms

Time:11-16

In my angular application there are two pages. In the first page we will fill the data in the form and click on continue then it goes to next page.

But there is back button in the next page and if we click on that then it will go to the before form page.

Now the main point is the data filled in form fields are not retaining the data.

So what can I do so that the values in form fields should be retained even after going to the next page and again coming back to the previous one.

Please help anyone.

CodePudding user response:

You need to save the state of the form either by using state managed libraries like NgRx or save the state in localStorage / sessionStorage.

You can opt-in to save the user state when clicks on continue button and go to next page. Once the user moves away to another page and tries to come back to form component, you would have that previous form state already saved either in form of local or session storage or by NgRx. All you need to do is read the data from state & call setValue() or patchValue() methods to prefill the form again!

Here are some examples that may be helpful:
How to persist value in angular reactive form?
How can I save user form values
https://www.bennadel.com/blog/3834-saving-temporary-form-data-to-the-sessionstorage-api-in-angular-9-1-9.htm

CodePudding user response:

While clicking on next button from first screen, save the form data in DB OR in localStorage and when user come back to this screen from next screen, get your data from DB back and populate in form using reactive form's

patchValue()

If data was saved in DB, you can pass some id in the router while redirecting back from the next screen, and get the data using API.

  • Related