1

I am using Angular2:

I am working on a Form Wizard based on the following:

1) each wizardstep(screen) is associated with its own Component rendering a separate subform () attached with ngFormControl bindings.

2) router/routing is applied to move forward thru the form

3) user input data are validated on each form individually [*]

4) user input data will be persisted, i.e. be sent to the API, after that the user has confirmed (in the last wizard step).

[*] I might be having some validationrules which are cross form in the future which span over multiple pages, i.e. forms. For now, this is out of scope for my question

I would like the user to navigate back and forth thru the wizard steps will retaining his user inputdata. What is the best way to go in Angular2 ?

(I have searched the net so far but I was not succesful in finding a suggestion on my problem (specific to angular2).)

user2120188
  • 427
  • 1
  • 4
  • 16

1 Answers1

1

The best way is to use a shared data service that is common to all components involved in the wizard.

export class SharedDataService {
  wizardData: any;
}

For this you can set it in the providers of the parent component that uses all of them:

@Component({
  (...)
  providers: [ SharedDataService ] // <----
}

You could also specify it when bootstrapping your application but it will be shared by all the application:

bootstrap(AppComponent, [ SharedDataService ]);

See this doc for more details:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thanks Thierry, ok I see. The traditional service (singleton pattern) approach. I had hopes that Angular2 would have brought some new constructs on the table. I read about the Angular2 canReuse and other lifecycle hooks of the angular router. I guess my solution should use these hookpoints to automatically save and restore form state (using the SharedDataService approach)...? – user2120188 May 25 '16 at 09:47
  • Hi Thiery, I want to put my forms (per wizard step: one form) on the SharedDateService capturing the state of userinput per form. My wizard lets the user navigate back and forth during userinput, that is switching formpages and still seeing userinput data previously entered.My state service has a change subscription on every form and there fore it is kept in sync with each formstate during userinput. When I navigate back to a form I initialize the (newly created) formModel with the previously saved values from my state service. Is there a better way to do this save/restore of form datavalues? – user2120188 May 30 '16 at 12:10