Exchange Data between multi step forms in Angular2: What is the proven way?

user2227400 picture user2227400 · Jul 7, 2016 · Viewed 7.8k times · Source

I can imagine following approaches to exchange Data between multi step forms:

1) Create a component for each form step and exchange data between components over @input, @output (e.g. you cannot change from step5 to 2)

2) Use the new property data in the new router (see here) (e.g. you cannot change from step5 to 2))

3) A shared Service (Dependency Injection) to store data (Component Interaction) (e.g. you can change from step5 to 2)

4) New rudiments with @ngrx/store (not really experienced yet)

Can you give some "gained experience values", what do you use and why?

Answer

nikk wong picture nikk wong · Sep 23, 2016

See my edit below.


Using SessionStorage is not strictly the 'angular' way to approach this in my opinion—a shared service is the way to go. Implementing routing between steps would be even better (as each component can have its own form and different logic as you see fit:

const multistepRoutes: Routes = [
  {
    path: 'multistep',
    component: MultistepComponent,
    children: [
      {
        path: '',
        component: MultistepBaseComponent,
      },
      {
        path: 'step1',
        component: MultistepStep1Component
      },
      {
        path: 'step2',
        component: MultistepStep2Component
      }
    ]
  }
];

The service multistep.service can hold the model and implement logic for components:

import { Injectable, Inject } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class MultistepService { 

  public model = {};
  public baseRoute = '/multistep';
  public steps = [

    'step1', 
    'step2'

  ];

  constructor (
    @Inject(Router) public router: Router) { };

  public getInitialStep() {

    this.router.navigate([this.baseRoute + '/' + this.steps[0]]);

  };

  public goToNextStep (direction /* pass 'forward' or 'backward' to service from view */): any {

    let stepIndex = this.steps.indexOf(this.router.url.split('/')[2]);

    if (stepIndex === -1 || stepIndex === this.steps.length) return;

    this.router.navigate([this.baseRoute + '/' + this.steps[stepIndex + (direction === 'forward' ? 1 : -1)]]);

  };

}; 

Good luck.


EDIT 12/6/2016


Actually, now having worked with the form API for a while I don't believe my previous answer is the best way to achieve this.

A preferrable approach is to create a top level FormGroup which has each step in your multistep form as it's own FormControl (either a FormGroup or a FormArray) under it's controls property. The top level form in such a case would be the single-source of truth for the form's state, and each step on creation (ngOnInit / constructor) would be able to read data for its respective step from the top level FormGroup. See the pseudocode:

   const topLevelFormGroup = new FormGroup({
       step1: new FormGroup({fieldForStepOne: new FormControl('')}),
       step2: new FormGroup({fieldForStepTwo}),
       // ...
   });

   ... 

   // Step1Component

   class Step1Component { 
       private stepName: string = 'step1';
       private formGroup: FormGroup;
       constructor(private topLevelFormGroup: any /* DI */) {
           this.formGroup = topLevelFormGroup.controls[this.stepName];
       }
    }

Therefore, the state of the form and each step is kept exactly where it should be—in the form itself!