So a few weeks ago I had accepted a take-home coding challenge where I had to create an Angular app where I had to implement a new user registration functionality among other things. For the registration form, I used Angular Reactive Forms, and to give it a modern look I decided to use a stepper using Angular material library. It’s really easy to implement a stepper with a reactive form using Material and I will describe my workflow as I how I achieved it.
Using Angular CLI I’ve created a new project and right away added angular material to the project.
ng new stepper-example
ng add @angular/material
For simplicity’s sake I set up the form in the app component using FormGroup and it had two parts: personal details and contacts info for a user. For the stepper, my plan was to show the first two parts of the form, and then the third window of the stepper was going to be a preview window before the user submit info. So after importing the forms and reactive forms module to the app module and importing it in the app I created a form in the app.component.ts file and it looked like this:
After that I created three new components for each part of the form that I was going to show in the stepper by using the CLI:
ng g c personal-details
ng g c contact-details
ng g c form-review
Before I proceeded to write any template code I imported all the necessary modules from Material in the app.module.ts and finally it looked like this:
After that I went to the App components template and basically implemented the stepper in there and for the steps of the stepper, I simply passed the components that I just created although I needed to actually need to go and take the forms and data that was going to be passed down from the parent(App). So after I was done implementing the stepper in the app template it looked like this:
After this, I went to the personal details component and using the @Input I extracted the form and used in the template as well. I repeated the same thing for other two components as well. So my three part stepper components looked like this :
Now All I needed to do was to just write out the template for the respective components and after I wrote all the templates the 3 component’s template files looked like this:
And in the browser it looked like this :
At that time even though I had validations required for few fields of the form the stepper was letting me go to the next step and as you can see on the review page my form inputs were all empty. It was really an easy fix, all I had to do was add ‘linear’ to the mat horizontal stepper in the App component’s template and it was fixed.
This is how quickly learned how to implement a stepper style form in Angular. Thank you for reading and any feedback and suggestions will be really appreciated.