Anthony
Anthony

Reputation: 2416

Angular multi step form routing

I am fairly new to angular and I'm building a multi step form using angular 4. Currently the component structure is as follows:

-apply.component
--step-one.component
--step-two.component
--step-three.component

Router is set up like this:

{
 path: '',
 redirectTo: '/apply',
 pathMatch: 'full'
},
{
 path: 'apply',
 component: ApplyComponent,
 children: [
   {
     path: 'personalInfo',
     component: StepOneComponent,
     outlet: 'step1'
   },
   {
      path: 'employmentInfo',
      component: StepTwoComponent,
      outlet: 'step2'
   }

Router outlets in ApplyComponent:

 <router-outlet name="step1">Child 1 in apply comp</router-outlet>
 <router-outlet name="step2">Child 2 in apply comp</router-outlet>

As the use completes one section, it should hide as the next sections shows. Each section is a router outlet on the parent component.

I am trying to figure out the best way to orchestrate the show/hide of each section. I have figured out how to activate each route from the previous route but how should I hide or destroy the previous route (section)? Should each section actually be generated in a ? How can I orchestrate interactions (go back/edit/next) for all of the different sections?

Edit: Another idea, should all the components be defined in the parent and then just show/hide as the move to next step and then update route? I might be thinking of this backwards in my current implementation of router updates components instead of components update route.

Upvotes: 0

Views: 2094

Answers (1)

Joel Richman
Joel Richman

Reputation: 1934

I would recommend using a single router-outlet to display the steps. Remove the named router outlet from your routes configuration and remove the name from the router outlet mark up. I assume you already have next and previous buttons to move between the steps. Now you don't have to worry about show/hide logic, the router takes care of that for you. You may need to add Route Guards to prevent the user from tampering with the url.

Your router config would look like this:

{
 path: 'apply',
 component: ApplyComponent,
 children: [
   {
     path: 'personalInfo',
     component: StepOneComponent
   },
   {
      path: 'employmentInfo',
      component: StepTwoComponent,
   }
}

Your single router outlet would look like this:

<router-outlet>Steps will be loaded here</router-outlet>

Upvotes: 2

Related Questions