Vinay
Vinay

Reputation: 962

Unique url for each step of multi-step form in angular2

So I have a SignUp Page in my website built with Angular2-Typescript. And this is a single component containing different steps/wiz-steps of signup. It looks like below,

enter image description here

I am simply making use of ng-if/ng-show/ng-hide method's to move on to next steps. But the url for all these steps remain the same like http://mysite/signup.

But I want a unique url for each steps,something like, http://mysite/signup/step1, http://mysite/signup/step2, and so on..

What is the best way to achieve this, without making much changes to the code?

Upvotes: 1

Views: 1109

Answers (1)

Radouane ROUFID
Radouane ROUFID

Reputation: 10813

You can take profit of child routes to perform that.

Suggestion :

1- In your route configuration, define the signup route as below :

 {
    path: 'signup',
    children: [
      { 
        path: '',
        redirectTo: '/step1',
        pathMatch: 'full'
      }, 
      {
        path: ':step',
        component: SignUpComponent
      }
    ]
  },

where :step is a path variable (Param) which you can make correspond to a typescript Enum.

export type SignUpStepEnum = "step1" | "step2" | "step3";

export const SignUpStepEnum {
   STEP1: <SignUpStepEnum>"step1",
   STEP2: <SignUpStepEnum>"step2",,
   STEP3: <SignUpStepEnum>"step3",
}

And in your SignUpComponent, subscribing on the params and displaying the step according of the enum value using a ngSwitch.

Example :

currentStep: SignUpStepEnum;

this.route.params.subscribe((params: { step: string }) => {
 this.currentStep = SignUpStepEnum[params.step];

if(!this.currentStep) {
//handle error when user is entering an incorrect step.
}

And in your view,

<div [ngSwitch]="currentStep">
        <step1 *ngSwitchCase="SignUpStepEnum.STEP1"></step1>
        <step2 *ngSwitchCase="SignUpStepEnum.STEP2"></step2>
        <step3 *ngSwitchCase="SignUpStepEnum.STEP3"></step3>
</div>

Upvotes: 3

Related Questions