Blog>
Snippets

Using Angular Material's Stepper for Multi-step Forms

Present a multi-step form approach using Angular Material's Stepper, showing validation and data persistence across different steps.
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'my-stepper',
  templateUrl: 'my-stepper.component.html',
  styleUrls: ['my-stepper.component.css'],
})
export class MyStepperComponent {
  isLinear = false;
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;

  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit() {
    this.firstFormGroup = this._formBuilder.group({
      firstCtrl: ['', Validators.required],
    });
    this.secondFormGroup = this._formBuilder.group({
      secondCtrl: ['', Validators.required],
    });
  }
}
Create an Angular component with a non-linear stepper. Two FormGroups are created for two steps inside the stepper, each requiring its own control validation.
<mat-horizontal-stepper [linear]="isLinear">
  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Fill out your first name</ng-template>
      <mat-form-field>
        <input matInput placeholder="First name" formControlName="firstCtrl" required>
      </mat-form-field>
      <button mat-button matStepperNext>Next</button>
    </form>
  </mat-step>
  <mat-step [stepControl]="secondFormGroup">
    <form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>Fill out your last name</ng-template>
      <mat-form-field>
        <input matInput placeholder="Last name" formControlName="secondCtrl" required>
      </mat-form-field>
      <button mat-button matStepperPrevious>Back</button>
      <button mat-button matStepperNext>Next</button>
    </form>
  </mat-step>
  <!-- You can add more steps here -->
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>
    <p>You are now done.</p>
    <button mat-button matStepperPrevious>Back</button>
  </mat-step>
</mat-horizontal-stepper>
The corresponding HTML template for the Angular Material stepper. It includes two steps with input fields for first and last name, and corresponding form groups for validation. Both steps have 'Next' and 'Back' buttons, provided by Material's API.