Create a Multi-Step Form in Angular
Multi-step forms are a common UX design technique that can boost usability by making the process easier for the user. As for the technical aspect, they can be challenging to manage and organize.
It’s possible to implement this by using a single large switch case in the template, but this has some drawbacks:
- We don’t have a link for each step.
- It’ll not be lazy-loaded.
- This makes the template hard to manage, and it violates the single responsibility principle.
Our goal is to solve everything above without introducing an extra layer where we have to store the form value and validity. Let’s look at how we can set up a multi-step form in Angular using the router and node injector. While this sample will have only two steps, the principles apply to forms with more steps as well.
We’ll create a container module that contains our form and two child modules — the account
and payment
modules. Angular CLI makes this a breeze. Simply run the following commands:
Now we can create our form in our container page component:
Using the node injector, we can now obtain a reference to the form. We can inject the Onboarding
component into our children directly, but I prefer to create an abstraction.
Let’s create a FormProvider
class:
Now let’s use it in our Onboarding
component:
Our class extends the FormProvider
class and uses DI to tell Angular to return the instance of this component when FormProvider
is requested. Now we can use it in our children components, for example:
Components can access the form validity and value and do what’s needed. It doesn’t need to be maintained in a store, and we’ve made it routable, lazy-loaded, and clean.
We can skip the FormProvider
functionality if each step is independent of the others and no valid reason exists to put the entire form in the container.
Follow me on Medium or Twitter to read more about Angular and JS!