Matthew
Matthew

Reputation: 11

Angular Material 2 matHorizontalStepper form validation

I am using matHorizontalStepper from Angular Material 5.2.4 with Angular 4/5. Linear mode is on. On step 1 I have a form with two inputs which are required. But stepper checks if only one required input is filled. It's enough for stepper that user filled only one required field and let the user go for the step 2.

Here's what I'm talking about https://angular-ugvs4m.stackblitz.io

What can I set stepper to validate if all required inputs are filled ?

Upvotes: 1

Views: 1896

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16837

I forked your stackblitz app and fixed your error. Live example

Your error was using the same control for the [stepControl], [formGroup] and for both inputs with formControlName (firstName and lastName).

You need to create a parent formGroup (firstFormGroup in your example), and then two FormControls inside it (firstName and lastName). The rest is just connecting it right in the html.

Also notice that I removed required from all the <input> elements. If you are using template driven forms, you do not need to put in on the html elements.

fixed component file

  ngOnInit() {
    this.firstFormGroup = this._formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required]
    });
    this.secondFormGroup = this._formBuilder.group({
      address: ['', Validators.required],
    });
  }

fixed html template

<mat-horizontal-stepper [linear]="true" #stepper="matHorizontalStepper">
  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Fill out your name</ng-template>
      <mat-form-field>
        <input matInput placeholder="First name"  formControlName="firstName">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Last name" formControlName="lastName" >
      </mat-form-field>
      <div>
        <button mat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>
  <mat-step [stepControl]="secondFormGroup">
    <form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>Fill out your address</ng-template>
      <mat-form-field>
        <input matInput placeholder="Address" formControlName="address" required>
      </mat-form-field>
      <div>
        <button mat-button matStepperPrevious>Back</button>
        <button mat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>
    You are now done.
    <div>
      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>
    </div>
  </mat-step>
</mat-horizontal-stepper>

Upvotes: 2

Related Questions